Char * w / Memory Leak
I have a problem with what is causing the memory leak in my program. Below is the code 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 can see that I have some memory that is definitely lost. To try and recreate the script 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 has no memory leaks according to valgrind. What am I not highlighting in my source code? What does my test code do that my original code doesn't? Thanks, I appreciate any help.
+3
source to share