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

(C) Memory leak

When a program dynamically creates new  ?instances by malloc without  ?freeing it in the end.

A common beginner's error is forgetting to call  ?free
{
  char * myString = malloc(sizeof(char)*10); //Allocate memory for 10 chars
  //Forget to write 'free (myString)'
}


Generate a memory leak

To see what  ?errors might occur.

  1. include <stdlib.h>
int main() { while(1) { int * i = malloc(10000000); } }


Note: I did not get noticed of an  ?error under C++ Builder 6.0. The program just leaked in silence.

Visual Studio

To prevent memory leaks in Visual Studio, when working in console application, add the lines below to your code.

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


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



last edited (February 7, 2007) by bilderbikkel, Number of views: 1702, Current Rev: 4 (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.