删除指向自动变量的指针

发布于 2024-10-06 00:02:48 字数 753 浏览 3 评论 0原文

请看一下这段代码,

int i = 10;                                     //line 1 
int *p = &i;                                    //line 2  
delete p;                                       //line 3 
cout << "*p = " << *p << ", i = " << i << endl; //line 4  
i = 20;                                         //line 5  
cout << "*p = " << *p << ", i = " << i << endl; //line 6  
*p = 30;                                        //line 7
cout << "*p = " << *p << ", i = " << i << endl; //line 8  

这段代码的结果是什么?尤其是3、5、7号线?他们会调用未定义的行为吗?输出会是什么?

编辑:我尝试使用 g++ 运行它,它编译并运行良好!我在 Windows 7 上使用 MinGW。

标准在这种情况下说了什么?

Please look at this code

int i = 10;                                     //line 1 
int *p = &i;                                    //line 2  
delete p;                                       //line 3 
cout << "*p = " << *p << ", i = " << i << endl; //line 4  
i = 20;                                         //line 5  
cout << "*p = " << *p << ", i = " << i << endl; //line 6  
*p = 30;                                        //line 7
cout << "*p = " << *p << ", i = " << i << endl; //line 8  

What is the result of this code? Especially of line 3, 5 and 7? Do they invoke undefined behavior? What would be the output?

EDIT : I tried running it using g++, and it's compiling and running fine! I'm using MinGW on Windows 7.

What does Standard say in this context?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

何其悲哀 2024-10-13 00:02:48

如果您曾经使用 new 动态分配过指针,则只能删除该指针。在这种情况下,您没有使用 new 分配指针,而是简单地将其定义并初始化为指向 int 类型的局部变量。

在未使用 new 动态分配的指针上调用删除称为未定义行为。简而言之,这意味着当执行这样的代码时,地球上任何事情都可能发生,并且您不能向这个星球上的任何人抱怨一点。

You can delete only a pointer if you have ever allocated it dynamically using new. In this case you have not allocated the pointer using new but simply defined and initialized it to point to a local variable of type int.

Invoking delete on a pointer not allocated dynamically using new is something called Undefined Behavior. In short, it means that anything on the earth can happen when such a code is executed and you can't complaint a bit to anyone on this planet.

眼眸印温柔 2024-10-13 00:02:48

delete p; 是 UB,因此无法预测或依赖任何进一步的行为。您的程序可能会立即崩溃,或者花掉所有的钱,或者只是退出 main() 并假装什么也没发生。

delete p; is UB and so any further behavior can't be predicted or relied upon. You program might crash immediately or spend all your money or just exit from main() and pretend nothing happened.

秋叶绚丽 2024-10-13 00:02:48

第 3 行绝对是未定义的行为,因为您试图删除不在堆上的地址处的内存。

Line 3 is definitely undefined behaviour, since you're trying to deleting memory at an address that is not on the heap.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文