[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppMemoryLeak
A common beginner's error is forgetting to call delete
You can prevent this memory leak using auto_ptr's (and auto_ptr's do more then only this):
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:
To prevent this error, use a vector instead.
To find out the allocation that causes the leak, elaborate with:
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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):
{ std::auto_ptr<MyClass>pMyClass(new MyClass); //No need to write 'delete pMyClass' }
- include <memory>
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.int main() { void* leak = malloc(1234); _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); }
- 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
External links
- How Bjarne Stroustrup deals with memory leaks: http://www.research.att.com/~bs/bs_faq2.html#memory-leaks
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
