-
using delete
How can I use delete to free up the memory in a 2D array? Do I need to call it for each of the rows in the array??
So say if I have
Code:
char **args = new char*[argc];
for(int i=0; i < argc; ++i) {
args[i] = new char[strlen(argv[i])+1];
strycpy(args[i], argv[i]);
}
And then I would like to free up the memory. Do I have to do something like the following:
Code:
for(int i=0; i < argc; ++i) {
delete [] args[i];
}
delete [] args;
or do I just need to do
Also, how can I tell if the memory has been freed??
And could anyone suggests a good tutorial on memory allocation in C++?
Thanks
Mark
-
This is right
Code:
for(int i=0; i < argc; ++i)
{
delete [] args[i];
}
delete [] args;
-
For every new[], you should have a matching delete [], which is why your first try is correct.
>> Also, how can I tell if the memory has been freed??
You cannot tell in code if memory is freed or not. You just need to design and code your program so that it always will be. Once you're running your code, there are different tools that you can use to detect memory leaks due to unfreed memory. Those depend on your compiler/IDE, platform, and how much effort you want to put into detecting the leaks.
Another, better way to handle memory management in C++ is to let the built-in tools do the work for you. For example, standard classes like vector are better solutions for dynamic arrays like you are using because they handle the allocation and deallocation of memory for you. The memory is automatically freed by the vector. The code for the allocation of your array of C style strings with the standard vector and string classes would be:
Code:
std::vector<std::string> args(argc);
for(int i=0; i < argc; ++i) {
args[i] = argv[i];
}
And the cleanup code would look like this:
Code:
// nothing required here