Adil
DevBest CEO
- May 28, 2011
- 1,278
- 716
One of the worst things you can do as a programmer is write applications which are prone to memory leaks. Here, I'll run through some quick methods on how to stop memory leaks (or at least cut down on their occurrences).
Spot the leak...
Found it?
If you haven't, don't worry.
The leak here is theoretically created when you create a new "MyClass" object on the heap. As you may know, the new keyword is a wrapper around C's malloc().
You're allocating the object but you aren't going to collect and dispose it once it goes out of scope.
MASSIVE NONO.
Now, let's fix that with delete.
Execution:
Plenary:
The whole point of this tutorial was to highlight how important the concept of using the delete keyword properly is.
So, some tips:
Spot the leak...
PHP:
MyClass *myClass = new MyClass();
If you haven't, don't worry.
The leak here is theoretically created when you create a new "MyClass" object on the heap. As you may know, the new keyword is a wrapper around C's malloc().
You're allocating the object but you aren't going to collect and dispose it once it goes out of scope.
MASSIVE NONO.
Now, let's fix that with delete.
PHP:
#include <iostream>
struct MyClass {
MyClass()
{
std::cout << "MyClass created.\n";
}
~MyClass()
{
std::cout << "Deallocated\n";
}
void MyFunction()
{
std::cout << "I am doing stuff\n";
}
};
int main( void )
{
MyClass *myClass = new MyClass();
myClass->MyFunction();
delete myClass;
return 0;
}
Execution:
- MyClass is initiated
- MyFunction is called
- MyClass is deallocated
Code:
adil@Zen:~/Desktop$ g++ main.cc
adil@Zen:~/Desktop$ ./a.out
MyClass created.
I am doing stuff
Deallocated
Plenary:
The whole point of this tutorial was to highlight how important the concept of using the delete keyword properly is.
So, some tips:
- Manage memory carefully
- When you call for an object to be disposed, delete it before it goes crazy
- Use new and delete accordingly