通过函数来处理内存 - 这是正确的
Deallocating memory through a function - is this right?
我只是有点困惑,为什么当我试图通过函数删除新分配的变量时正在打印相同的内存地址,我猜没有记忆被泄漏或指针悬挂。
印刷了相同的内存地址。
#include <iostream>
using namespace std;
void deallocater(int *p)
{
delete p;
p = nullptr; // memory deleted and no dangling pointer right?
}
int main()
{
int *x = new int(1);
cout<<x;
deallocater(x);
cout<<endl<<x; // why is the same memory address being printed?
return 0;
}
我假设该功能成功
调用函数
void deallocater(int* p)
{
delete p;
p = nullptr;
}
通过
deallocater(x);
将x
的值复制到p
。因此,在deallocater()
中,本地变量p
分配了nullptr
。但是,调用程序的变量x
不会更改。
您可以通过参考来实现您似乎想要的东西:
void deallocater(int* &p)
{
delete p;
p = nullptr;
}
然而,内存分配和分配不应分为不同且无关的功能,以避免悬挂指针和/或内存泄漏的危险。相反,良好的C 代码几乎不包含任何delete
语句和少量new
语句(以初始化智能指针(,而是使用标准库构造(容器和智能指针(进行内存管理。
代码无法更改deallocater()
中指针p
的内容,因此打印时仍显示相同的值。呼叫后,p
仍然具有相同的(指针(值,但是它指向的内存已释放。这被称为"悬空参考"。
要更新指针,使用双分球或对指针的引用:
void deallocater(int **p)
{
delete *p;
*p = nullptr; // memory deleted and no dangling pointer right?
}
int main()
{
int *x = new int(1);
cout<<x;
deallocater( &x );
cout<<endl<<x; // why is the same memory address being printed?
return 0;
}
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- 对具有动态分配的内存和析构函数的类对象的引用
- 调用析构函数以释放动态分配的内存
- std::unordered_map析构函数不释放内存?
- 为什么类和 main() 函数中也有动态内存分配
- 为什么此函数会导致内存泄漏?
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 在函数中分配内存时出现问题
- 在没有动态内存的世界中,我是否需要虚拟析构函数?
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 在构造函数中分配内存失败是如何冒泡的
- 将 vector<vector<int>> 传递到函数中会产生内存错误
- 在 Microsoft Access SQL 中调用自定义 DLL 函数时传递的内存地址无效
- 如何在 c++ 中的析构函数中正确释放合并 LL 的内存?
- 为什么 free() 函数不将内存返回给操作系统?
- 从函数返回时C++内存管理
- 无法在循环中动态分配内存(函数会吃掉所有内存)
- 在c++中使用C动态内存函数避免分段错误
- 用C/ c++在Windows上解压缩内存函数