Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char * w/ Memory Leak

I have an issue identifying what is causing the memory leak in my program. Below is the code that I am running:

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] = NULL;

    //...
    //...

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

Running this code through valgrind, I see that I have memory that is definitely lost. To attempt to recreate the scenario and debug, I have a smaller scale version of the above code here:

int main()
{
    char* var[999];
    string s = "1234";

    var[0] = new char[4 + 1];
    strcpy(var[0], s.c_str());

    delete [] var[0];
    return 0;
}

This code does not have any memory leaks according to valgrind. What am I not de-allocating in my original code? What is my test code doing that my original code is not doing? Thank you, I appreciate any help.

like image 723
mas4 Avatar asked Mar 31 '26 19:03

mas4


2 Answers

You usually need to declare your char*'s with a new if you are going to use delete[] on it later in the code. Looks like just a simple mistake.

like image 132
phung001 Avatar answered Apr 03 '26 09:04

phung001


I'm new in c++ but you should declare input as follows

char **input=new char*[999];
like image 45
Jonathan Arley Monsalve Salaza Avatar answered Apr 03 '26 08:04

Jonathan Arley Monsalve Salaza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!