[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CMemoryLeak
A common beginner's error is forgetting to call ?free
Note: I did not get noticed of an ?error under C++ Builder 6.0. The program just leaked in silence.
To find out the allocation that causes the leak, elaborate with:
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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.int main() { while(1) { int * i = malloc(10000000); } }
- include <stdlib.h>
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.int main() { void* leak = malloc(1234); _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); return 0; }
- include <crtdbg.h>
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
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
