简体   繁体   中英

Char* Array Memory Leak

I am having issues de-allocating memory that I used in my char* array. In my code snippet below, I am creating a char* array named input that holds pointers to single words at a time followed by a pointer NULL at the end of the array. This is the only time (I believe) I allocate memory in my code.

char* input[999];
//exec commands 
for(unsigned int i = 0; i < commands.size(); i++)
{
    string current = "";
    string word = "";
    int k = 0;
    for(unsigned int j = 0; j < commands.at(i).size(); j++) //iterate through letters
    {
        current = commands.at(i);
        //cout << "current: " << current << endl;
        if(current[j] == ' ')
        {
            input[k] = new char[word.size() + 1];
            strcpy(input[k], word.c_str());
            k++;
            word = "";
        }
        else
            word += current[j]; //add letter
        //cout << "word: " << word << endl;
    }
    input[k] = new char[word.size() + 1];
    strcpy(input[k], word.c_str());
    k++;
    input[k] = new char[1]; //add the NULL char *
    input[k] = NULL;
    ...

Later on, I attempt to de-allocate this memory with this snippet of code:

for(int z = 0; z < k; z++)
{
    delete[] input[z];
}

I am iterating through my char* array and deleting the memory allocated at each index. Without using this snippet, valgrind informs me of memory leaks. Using this snippet, valgrind informs me of less memory leaks than before. I am still stuck with the issue of memory still being definitely lost .

I am unsure what I am missing to remove the rest of the allocated memory (or if the cause of the rest of the memory leaks is in fact somewhere else in my code). I appreciate any and all help, suggestions, and tips.

I think, your problem is in below case,

input[k] = new char[1]; //add the NULL char *
input[k] = NULL;

here, without free -ing input[k] , you're assigning NULL to it. Thus, the previous input[k] is lost.

If you really want input[k] to hold NULL , ( maybe as a sentinel value ), you can simply do

input[k] = NULL;

No need to allocate memory separately.

You don't need to create a new char on where it says input[k] = new char[1]; //add the NULL char * input[k] = new char[1]; //add the NULL char * Just leave the NULL assignment in and it should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM