为什么我的悬摆指针不会导致段错误? [英] Why my dangling pointer doesn't cause a segmentation fault?
本文介绍了为什么我的悬摆指针不会导致段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = (int *)malloc(sizeof(int));
free(p);
*p = 42;
return 0;
}
我创建了一个指针,那么我把它指向分配的空间,最后我已经指派42到它。
在我看来,这不应该工作,应该引起分段错误,但它的作品。
那么,为什么?
I created a pointer, then I pointed it to allocated space and finally I had assigned 42 to it. In my opinion it should not work, it should cause a segmentation fault, but it works. So, why?
PS:我通常使用GCC编译它在Linux
PS: I normally compiled it with Gcc on Linux
推荐答案
纯粹是运气。在这种情况下,行为的未定义。即:没有期望可制成到可能发生的事情。
Pure luck. The behavior in this case is undefined. I.e.: no expectations can be made as to what may happen.
这篇关于为什么我的悬摆指针不会导致段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文