简体   繁体   English

如何检查内存的释放

[英]How to check deallocation of memory

如何检查指针p指向的内存是否已成功释放?

In few words: you can't. 简而言之:您不能。

Check out tools like Valgrind to help you debugging memory leaks issues. 查看类似Valgrind的工具,以帮助您调试内存泄漏问题。

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, 释放指针后,将其设置为0,以便进一步delete无效,
  • Use standard classes ( vector , ...) instead of rolling your own, 使用标准类( vector ,...)而不是自己滚动,
  • Finally, don't use pointers (actually you almost can) 最后,不要使用指针(实际上您几乎可以使用)

抱歉,很简短的回答“你不能”

使用IBM Rational Purify工具检查内存的正确释放。

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. 毕竟,您调用C / C ++运行时来释放内存,但是C / C ++运行时也调用操作系统的功能来释放页面。 You could even have a custom memory allocator on top of the C/C++ runtime that eg uses caching to implement a faster memory allocation algorithm. 您甚至可以在C / C ++运行时之上使用自定义内存分配器,例如使用缓存来实现更快的内存分配算法。

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. 可能发生任何事情,只是不再使用该指针。

Exception handling. 异常处理。 Ie try/catch blocks. 即尝试/抓住块。

  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 使用valgrind检查是否有内存泄漏
  3. Avoid raw pointers - use smart pointers instead 避免使用原始指针-改用智能指针

In C++, you can safely assume deallocation never fails. 在C ++中,您可以放心地认为释放不会失败。 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. 不过,这本身并不是释放的问题-原始delete成功完成了。 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... 如果程序尝试两次删除一个指针,这是程序内存管理的问题,但是对于现代STL和智能指针(如std::vectorstd::unique_ptr等)来说,这几乎是不必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM