[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppMemoryLeak

(C++) Memory leak

When a program dynamically creates new instances of classes without freeing it in the end.

A common beginner's error is forgetting to call delete
{
  MyClass * pMyClass = new MyClass;
  //Forget to write 'delete pMyClass'
}


You can prevent this memory leak using auto_ptr's (and auto_ptr's do more then only this):

  1. include <memory>
{ std::auto_ptr<MyClass>pMyClass(new MyClass); //No need to write 'delete pMyClass' }


Another common beginner's error is to generate an array dynamically, without calling delete[]. They either forget it in total, or use the 'plain' delete:

{
  double * pArray = new double[1000];
  //Forgot to call 'delete[] pArray'
}
{
  double * pArray = new double[1000];
  delete pArray; //MEMORY LEAK!!!
  //Forgot to call 'delete[] pArray'
}
{
  double * pArray = new double[1000];
  delete[] pArray; //Correct!
}


To prevent this error, use a vector instead.

Generate a memory leak

To see what errors might occur:

int main()
{
  while (1)
  {
    int * i = new int[10000000];
  }
}


Visual Studio

To prevent memory leaks in Visual Studio, when working in console application, add the lines below to your code. When working with the  ?MFC it does this automatically.

  1. include <crtdbg.h>
int main() { void* leak = malloc(1234); _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); }


To find out the allocation that causes the leak, elaborate with:

int __cdecl MyAllocHook(
  int                    //nAllocType,
  void   *               //pvData,
  size_t                 //nSize,
  int                    //nBlockUse,
  long lRequest,
  const unsigned char *  //szFileName,
  int                    //nLine
  )
{
  //Set a conditional breakpoint to break on the leaking 'lRequest'
  return true; // Allow the memory operation to proceed
}
void* leak()
{
	return malloc(1234);
}
int main()
{
  _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  _CrtSetAllocHook( MyAllocHook );
  leak();
}


'Memory leak' links

External links



last edited (May 6, 2007) by bilderbikkel, Number of views: 2571, Current Rev: 8 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.