Avoid Memory Leaks While Coding in C Plus Plus
Contents
Instructions
Things You’ll Need
- Proficiency in C++
- C++ compiler
- Debugger and other investigative software tools
Part 1
Understand the operator basics. The C++ operator new
allocates heap memory. The delete
operator frees heap memory. For every new
, you should use a delete
so that you free the same memory you allocated:
|
|
Part 2
Reallocate memory only if you’ve deleted. In the code below, str
acquires 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:
|
|
Part 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:
|
|
Part 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:
|
|
Part 5
Pay attention to the square braces after “delete.” Use delete
by itself to free a single object. Use delete []
with square brackets to free a heap array. Don’t do something like this:
|
|
Keep Learining, Keep Practicing. :) :)
Thatβs All. π
Thanks for reading. π
If you liked it feel free to share with your dear ones.π
And tell me what do you think in the comment box.π¬
Stay tuned with CS111.
Author Vikash Patel
LastMod May 4, 2021