删除指向自动变量的指针
请看一下这段代码,
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您曾经使用 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.
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 frommain()
and pretend nothing happened.第 3 行绝对是未定义的行为,因为您试图删除不在堆上的地址处的内存。
Line 3 is definitely undefined behaviour, since you're trying to deleting memory at an address that is not on the heap.