这会导致c++中的内存泄漏吗?
Will this cause a memory leak in c++?
int* alloc()
{
int* tmp = new int;
return tmp;
}
int main()
{
int* ptr = alloc();
......
......
delete ptr;
return 0;
}
这里我没有释放tmp,但是显式释放了ptr。tmp也会吗?被释放,因为PTR和TMP指的是同一位置?
如果不是,那么指针tmp会发生什么?它会导致内存泄漏吗?
不,这不会导致内存泄漏。内存泄漏是已分配但未返回(当它们不再使用时)的缓冲区(内存块)。在你的alloc()
函数,tmp
不是一个缓冲区…它是一个变量,在调用new
之后,保存缓冲区的地址。您的函数返回此地址,在main()
中,该地址存储在ptr
变量中。当您稍后调用delete ptr
时,您正在释放ptr
指向的缓冲区,因此缓冲区已被释放,并且没有泄漏。
你的程序不会导致内存泄漏只要没有抛出未捕获的异常。
你可以做得更好,让它100%防弹,像这样:
#include <memory>
std::unique_ptr<int> alloc()
{
std::unique_ptr<int> tmp { new int };
//... anything else you might want to do that might throw exceptions
return tmp;
}
int main()
{
std::unique_ptr<int> ptr = alloc();
// other stuff that may or may not throw exceptions
// even this will fail to cause a memory leak.
alloc();
alloc();
alloc();
auto another = alloc();
// note that delete is unnecessary because of the wonderful magic of RAII
return 0;
}
早点养成这个习惯。
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏