通过函数来处理内存 - 这是正确的

Deallocating memory through a function - is this right?

本文关键字:内存 函数 处理      更新时间:2023-10-16

我只是有点困惑,为什么当我试图通过函数删除新分配的变量时正在打印相同的内存地址,我猜没有记忆被泄漏或指针悬挂。

印刷了相同的内存地址。

#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;
}