c++ - 删除 ptr C++ 后会发生什么

标签 c++ pointers printing delete-operator dangling-pointer

<分区>

我尝试使用以下代码示例删除一个 ptr:

int* data = new int(1);

int* p = NULL; 

p = data;

*p = 3;

delete p;

// Prints 3
cout << *p << endl;

//Prints 3    
cout << *data << endl;

The last two lines of code prints 3, and my question is what is deleted after delete p? According to what it prints out from the last two lines of code, it seems like nothing is deleted 0.0~~

有人请给我解释一下。提前谢谢大家。

最佳答案

在您删除对象后取消引用指针是导致未定义行为的原因。不要指望任何可预测的行为并避免它。

由于角度不同和未定义行为导致的悬垂指针异常读取:Can a local variable's memory be accessed outside its scope?

关于c++ - 删除 ptr C++ 后会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54663307/

相关文章:

C++:指向结构中成员函数的指针

javascript - 如何通过 JavaScript 访问打印机 SNMP 数据

html - 分页后重复表格标题

c++ - 根据对父类(super class)的引用确定对象标识

c++ - OpenGL独占模式全屏

c++ - 迭代 std::list<boost::variant>

c++ - 如何设计一个C++类?

c++ - 如何使用指针和指针运算

c++ - 自 C++17 起使用 std::launder 到 "validate"非 "pointer to object"指针值

java - 数组项目似乎只打印出null