I am a C++ programmer on the Windows platform. I am using Visual Studio 2008.
I usually end up in the code with memory leaks.
Normally I find the memory leak by inspecting the code, but it is cumbersome and is not always a good approach.
Since I can’t afford a paid memory leak detection tool, I wanted you guys to suggest the best possible ways to avoid memory leaks.
- I want to the know how the programmer can find memory leaks.
- Is there any standard or procedure one should follow to ensure there is no memory leak in the program?
Instructions
Things You’ll Need
1
Understand the operator basics. The C++ operator
newallocates heap memory. Thedeleteoperator frees heap memory. For everynew, you should use adeleteso that you free the same memory you allocated:2
Reallocate memory only if you’ve deleted. In the code below,
stracquires a new address with the second allocation. The first address is lost irretrievably, and so are the 30 bytes that it pointed to. Now they’re impossible to free, and you have a memory leak:3
Watch those pointer assignments. Every dynamic variable (allocated memory on the heap) needs to be associated with a pointer. When a dynamic variable becomes disassociated from its pointer(s), it becomes impossible to erase. Again, this results in a memory leak:
4
Be careful with local pointers. A pointer you declare in a function is allocated on the stack, but the dynamic variable it points to is allocated on the heap. If you don’t delete it, it will persist after the program exits from the function:
5
Pay attention to the square braces after “delete.” Use
deleteby itself to free a single object. Usedelete []with square brackets to free a heap array. Don’t do something like this:6
If the leak yet allowed – I’m usually seeking it with deleaker (check it here: http://deleaker.com).