c – 使用已删除的指针地址

(*)据我所知,标准允许实现修改删除操作符的操作数,但是大多数实现不会这样做.
int* ptr = new int(0);
delete ptr; //delete is allowed to modify ptr,for example set it to 0
std::cout << ptr; // UB?

确认(*),是否读取ptr(以打印的形式)定义良好?

如果删除修改ptr,是否允许设置陷阱值,这将使读取ptr UB?

解决方法

在C 14中这是实现定义的行为,[basic.stc.dynamic.deallocation] / 4:

If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value,the deallocation function shall deallocate the storage referenced by the pointer,rendering invalid all pointers referring to any part of the deallocated storage.

Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.

一个脚注:

Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault.

这是从C11开始变化的,粗体字表示“未定义行为”,没有脚注.

所以要回答你的问题,删除ptr;被允许设置一个陷阱值,该值将导致std :: cout的运行时故障<< PTR.编译器文档必须指定行为.这是比UB更窄的限制,在这种情况下,任何不稳定的行为都是允许的.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...