C++: Deleting Allocated Memory
When we create a variable, its usually allocated to memory and then deleted when the function is finished.
When we create a pointer for example we are allocating memory, and if we decide to declare it with the new keyword the system does not automatically delete the allocated memory.
Whenever you use 'new', you are allocating memory which unless you delete it will not be deleted; this will eventually clog up your system, remember the system isn't going to clean up for you.
For example the following would create a pointer which allocates memory for itself and then does not remove the allocated memory:
#include <iostream>
using namespace std;
int main(){
int z = 8;
int*ptr = new int;
*ptr = z;
cout << *ptr << endl;
system("PAUSE");
return 0;
}
Right know your probably thinking "Ok then.. So how can I delete these variables after creation?", well the answer to that is we use the delete keyword, we could delete the above pointer like so:
#include <iostream>
using namespace std;
int main(){
int z = 8;
int*ptr = new int;
*ptr = z;
cout << *ptr << endl;
delete ptr;
system("PAUSE");
return 0;
}
Now the memory for that variable is completely free!
And before anyone asks, no you don't need to say "delete *ptr", well this is because we don't want to delete the variable z, we want to delete all of the memory starting at the location which the pointer contains, so for that we just use the pointers name as it is.
Its often very useful to delete things in destructors.
REMEMBER DELETE THOSE THINGS THAT USE NEW!!!
Back to C++

