How to check if memory to which pointer p points has been succesfully deallocated?
In few words: you can't.
Check out tools like Valgrind to help you debugging memory leaks issues.
Some other things you should consider:
- Use smart pointers so that you don't have do think about memory management,
- Set your pointers to 0 after you free them, so that a further
delete
has no effect, - Use standard classes (
vector
, ...) instead of rolling your own, - Finally, don't use pointers (actually you almost can)
delete p; p = 0;
is UB ? –
Nebulosity delete p; *p = 0
is UB. I do not mean to access the pointed-to memory, only the variable holding its (now non valid) address. –
Nebulosity delete p; p = p;
is UB if p
was not null initially. –
Salvador Use IBM rational purify tool to check correct deallocation of memory.
Define successfully! Define deallocated!
After deallocating memory (whether it is free or delete) you must not use that pointer again. All other assumptions are irrelevant.
After all, you call the C/C++ runtime to deallocate memory, but the C/C++ runtime also calls functions of the operating system to free the page. You could even have a custom memory allocator on top of the C/C++ runtime that e.g. uses caching to implement a faster memory allocation algorithm.
All of these layers may keep the deallocated memory for themselves (because of fragmentation or just because they like to keep it to themselves) or may tell the underlying layer to deallocate it. Anything can happen, just don't use that pointer anymore.
- Some tools which are doing static code analysis can point some problems regarding the memory deallocation.
- Use valgrind to check whether you have memory leaks
- Avoid raw pointers - use smart pointers instead
Exception handling. I.e. try/catch blocks.
In C++, you can safely assume deallocation never fails. Destructors must not throw exceptions, and the actual memory reserved should never fail to be released, so given those two points, nothing can go wrong.
However, if you delete a pointer that has already been deleted, your program will probably crash. This isn't a problem with deallocation itself though - the original delete
worked successfully. It's a problem with your program's memory management if it tries to delete a pointer twice, but that's rarely necessary with modern STL and smart pointers like std::vector
, std::unique_ptr
, etc...
© 2022 - 2024 — McMap. All rights reserved.