By removing char ** correctly?

I created a 2d array of c-strings using:

char ** my_array = new char*[N];

and then I initialized each line using:

my_array[i] = new char[M]; // where M is a varying number. assign values to my_array[i] later

So, I pretty much got a 2d gear array.

I wanted to continue and delete it all as follows:

for(int i = 0; i < N; i++)
{ delete [] my_array[i]; }

and then:

delete [] my_array;

the for loop gave me HEAP CORRUPTION ERROR - why?

************** UPDATE - full code **********************

#define BOOST_TEST_MODULE ARGS
#define BOOST_LIB_DIAGNOSTIC

#include <string>
#include <vector>
#include <iostream>
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/assign.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/assign/std/vector.hpp>

using namespace std;
using namespace boost;
using namespace boost::assign;

typedef vector<string> string_array;

BOOST_AUTO_TEST_CASE(test1)
{
    string_array args = list_of
        ("aaa")("bbbb")("ccccccc")("dd")("eeeeeeeee")("ff")("g")("hhh");

    string_array tokens;

    string arg = "";
    for(int i = 0; i < (int)args.size(); i++)
    {
        arg += args[i];
        if(i != (int)args.size() - 1)
                arg += " ";
    }

    split(tokens, arg, is_any_of(" "));

    char ** new_args = NULL;
    new_args = new char*[(int)tokens.size() + 1];
    new_args[(int)tokens.size()] = 0;
    for(int i = 0; i < (int)tokens.size(); i++)
    { 
        new_args[i] = new char[(int)tokens[i].size()];
        for(int j = 0; j <= (int)tokens[i].size(); j++)
        {
            if(j == (int)tokens[i].size())
                new_args[i][j] = '\0';
            else
                new_args[i][j] = tokens[i][j];

        }
    }

    for(int i = 0; i < (int)tokens.size(); i++)
    { 
        std::cout << new_args[i] << std::endl; 
    }

    for(int i = (int)tokens.size() - 1; i >= 0; i--)
        delete new_args[i]; 

    delete [] new_args;
}

If you don’t have a raise: convert BOOST_AUTO_TEST_CASE to main () and voil.

What happens above: converts a vector to char **

+3
source share
3 answers

tokens [i].size() tokens [i] ', 0 ' tokens [i].size() '. . 0 'tokens [i].size()', tokens [i].size() + 1 '.

+3

. , - .

, , - . , .

, valgrind.

+6

Your description sounds correct, but the code you posted is incomplete. In particular, if you only call

my_array[i] = new char[M];

for some elements of the array (not all N), then you will have garbage in other elements, which will lead to detection of the heap found in the delete cycle.

+2
source

Source: https://habr.com/ru/post/1719905/


All Articles