gpt4 book ai didi

c++ - 为什么使用delete会导致core dump?

转载 作者:行者123 更新时间:2023-12-03 02:50:26 30 4
gpt4 key购买 nike

我目前正在使用 Kubuntu 19.04 Kate 18.12.3 和 g++ (Ubuntu 8.3.0-6ubuntu1) 8.3.0 自学 C++

在 Kate 的“工具/模式/源”菜单中,我选择 C++ 或 ISO C++。

我编写了一个小程序,其目的是修复上一个练习中出现的故意内存泄漏。这是我的代码。

/* Fix the program from Exercise 6. */

#include <iostream>

int myFunction(int * pInt);

int main()
{
int myVar;
int * pInt = new int;
pInt = &myVar;
*pInt = myFunction(&myVar);
std::cout << "The value of myVar is " << *pInt << std::endl;
delete pInt; // Free up pointer.
pInt = 0; // Make pointer safe.
return 0;
}

int myFunction(int * pInt)
{
*pInt = 2;
return *pInt;
}

当我通过 g++ 传递此代码时,会生成以下输出。

myVar 的值为 2munmap_chunk():无效指针中止(核心转储)

但是,当删除指令被注释掉时,会生成以下输出。

myVar 的值为 2

鉴于delete是C++中的标准关键字,为什么在此代码中使用它会导致核心转储?

我无法理解这一点,并且非常感谢您能提供的任何帮助。

最诚挚的问候,

斯图尔特

最佳答案

在此声明中

pInt = &myVar;

您已经覆盖了 new int 返回的先前值,并将其替换为指向局部变量的指针。这就是 delete 崩溃的原因(从技术上讲,它是 undefined behaviour ),因为 operator delete无法释放局部变量,只能释放使用相应 new 运算符分配的内容。

当您重新分配指针后,您将无法访问 new 返回的指针。这是memory leak .

关于c++ - 为什么使用delete会导致core dump?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58710853/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com