How to check deallocation of memory

前端 未结 7 1314
猫巷女王i
猫巷女王i 2020-12-03 21:59

How to check if memory to which pointer p points has been succesfully deallocated?

相关标签:
7条回答
  • 2020-12-03 22:18

    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)
    0 讨论(0)
  • 2020-12-03 22:20

    Sorry, very short answer "You can't"

    0 讨论(0)
  • 2020-12-03 22:23

    Exception handling. I.e. try/catch blocks.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 22:26
    1. Some tools which are doing static code analysis can point some problems regarding the memory deallocation.
    2. Use valgrind to check whether you have memory leaks
    3. Avoid raw pointers - use smart pointers instead
    0 讨论(0)
  • 2020-12-03 22:37

    Use IBM rational purify tool to check correct deallocation of memory.

    0 讨论(0)
提交回复
热议问题