为什么释放C ++中未定义的无效指针?(Why is freeing invalid pointers left undefined in C++?)

编程入门 行业动态 更新时间:2024-10-26 04:31:12
为什么释放C ++中未定义的无效指针?(Why is freeing invalid pointers left undefined in C++?)

考虑以下程序:

#include <iostream> int main() { int b=3; int* a=&b; std::cout<<*a<<'\n'; delete a; // oops disaster at runtime undefined behavior }

好的,根据C ++标准,程序的行为是不确定的。 但我的问题是为什么它没有定义? 为什么C ++的实现不提供任何编译器错误或任何警告? 是否真的很难确定指针的有效性(意味着检查指针在编译时是否由new返回?)是否有任何开销用于静态确定指针的有效性(即编译时间)?

Consider following program:

#include <iostream> int main() { int b=3; int* a=&b; std::cout<<*a<<'\n'; delete a; // oops disaster at runtime undefined behavior }

Ok, behavior of program is undefined according to C++ standard. But my question is why it is left undefined? Why implementations of C++ don't give any compiler errors or any warnings? Is it really hard to determine validity of pointer (means to check whether pointer is returned by new at compile time?) Is there any overhead involved to determine validity of pointer statically (i.e. compile time)?

最满意答案

在编译时不可能确定指针指向什么,下面是一个例子来说明这一点:

volatile bool newAlloc; int main() { int b=3; int* a; if(newAlloc) { a = new int; } else { a = &b; } std::cout<<*a<<'\n'; delete a; // impossible to know what a will be }

It is impossible to determine what a pointer points to at compile time, here is an example to illustrate this:

volatile bool newAlloc; int main() { int b=3; int* a; if(newAlloc) { a = new int; } else { a = &b; } std::cout<<*a<<'\n'; delete a; // impossible to know what a will be }

更多推荐

本文发布于:2023-08-03 19:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1396245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   中未   定义   freeing   undefined

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!