微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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更窄的限制,在这种情况下,任何不稳定的行为都是允许的.

原文地址:https://www.jb51.cc/c/116411.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐