Tuesday, 3 January 2012

Auto de-allocation of dynamic memory.

Auto de-allocation of dynamic memory.

Interesting.. I write a function which has many return points. Assume i use x number of dynamic memory variables,
and of course it is my responsibility to de-allocate all the dynamic memories while i return from the function to avoid memory leaks. Wow, It is possible without any dedicated techniques in basic programming. I can write a function with all variables as a actual parameters, and invoke the same whenever i return  from the function. Wait.. people complains me that is a stupid programming. :(. what if someone takes care of dyamic memory deallocation when i return from the function.

Yes, Convert the pointer to Auto pointer, while stackwinding auto pointers are deallocated automatically. Wow My headache is cured!!!!..

Let's check.

#include <iostream>
#include <string>
#include <memory>
using namespace std;

void func ()
{
  int *ptr1 = new int;
  *ptr1=100;

  auto_ptr<int> ptr2 (new int);
 *ptr2 = 200;
 cout <<"ptr1 "<<*ptr1<<endl;
cout <<"ptr2 "<<*ptr2<<endl;


}


int main ( int argc, char ** argv)
{
  func ();
}

Ooops. i have leaked 4 bytes by ptr1 in func (), and valgrind catched it... :)

valgrind --tool=memcheck <exeutable>

....
==16739== LEAK SUMMARY:
==16739==    definitely lost: 4 bytes in 1 blocks
==16739==    indirectly lost: 0 bytes in 0 blocks
==16739==      possibly lost: 0 bytes in 0 blocks
==16739==    still reachable: 0 bytes in 0 blocks
==16739==         suppressed: 0 bytes in 0 blocks
...


I changed 'ptr1' to auto pointer and then checked the memory leak..


#include <iostream>
#include <string>
#include <memory>
using namespace std;

void func ()
{
  auto_ptr<int> ptr1(new int);
  *ptr1=100;

  auto_ptr<int> ptr2 (new int);
 *ptr2 = 200;
 cout <<"ptr1 "<<*ptr1<<endl;
cout <<"ptr2 "<<*ptr2<<endl;


}


int main ( int argc, char ** argv)
{
  func ();

}

....
==16750== HEAP SUMMARY:
==16750==     in use at exit: 0 bytes in 0 blocks
==16750==   total heap usage: 2 allocs, 2 frees, 8 bytes allocated
==16750==
.....

So, so... Use auto pointer whenever you like to do auto dealocation. :).

No comments:

Post a Comment