Reputation: 1049
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.
Upvotes: 3
Views: 126
Reputation: 103
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.
Upvotes: 2
Reputation: 353
I'm new in c++ but you should declare input as follows
char **input=new char*[999];
Upvotes: 1