[C/C++]Memory Leaks

Status
Not open for further replies.

Adil

DevBest CEO
May 28, 2011
1,276
714
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...
PHP:
MyClass *myClass = new MyClass();
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.

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
Run this through G++ or another compiler;
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
I will be writing some better & more informative tutorials soon.
 

Habbos

Member
Jul 3, 2010
140
4
That's nice keep up the good work I'm not that good at what you're doing but this sure was very informative thanks
 

Adil

DevBest CEO
May 28, 2011
1,276
714
Thanks guys, I'll add one soon-ish (hopefully today or tomorrow).
 
Status
Not open for further replies.

Users who are viewing this thread

Top