Monday, October 5, 2009

What's Wrong with this Code?


doFoo()
{
  int x = 10;
  Foo *foo = new Foo();
  for ( int i = 0; i < 100; ++i )
  {
    x += i;
    foo->add(x);
  }
}


Easy right? We forgot to free the memory associated with the pointer foo. This is what we call a memory leak!

Fix:

doFoo()
{
  int x = 10;
  Foo *foo = new Foo();

  for ( int i = 0; i < 100; ++i )
  {
    x += i;
    foo->add(x);
  }
  
  delete foo; // this frees up the memory associated with the pointer foo.
}

What if we had an array of Foo's ?


 Foo *foos = new Foo[100];
 // ...
 delete [] foos;

No comments:

Post a Comment