【发布时间】:2020-09-30 16:38:04
【问题描述】:
所以,我有这个代码:
#include <stdio.h>
int main()
{
char *p;
int var = -1;
int i;
/* Printing all memory we can read */
p = (char *)&var;
/* No stopping condition. The OS will stop us */
for (i = 0;; i++)
{
printf("(%i) %i\n", i, p[i]);
/*
* The next statement also tries to write a zero
* starting from &var. Try to uncomment and explain ...
*/
//p[i] = 0;
}
}
以这种方式,它会出现应有的分段错误,输出:
..................
(6556) 108
(6557) 116
..................
(6582) 0
(6583) 0
Segmentation fault
取消注释上面的这行代码:p[i] = 0;
它不会出现分段错误,输出是这样的:
..........
(1) 0
(2) 0
(3) 0
(4) 4
(1) 0
(2) 0
(3) 0
(4) 4
(1) 0
(2) 0
(3) 0
(4) 4
(1) 0
^C
i have to interrupt it
不明白为什么会这样,而且看起来 i 没有增加
【问题讨论】:
-
这是未定义的行为,您无法对其进行可靠的推理。您可以在调试器汇编模式下运行这两个代码,并准确查看在您的特定情况下发生了什么。不过,这并不是一个非常有见地的课程。
-
虽然这确实是未定义的行为,但“幕后”发生的事情很可能是通过将零写入内存而不允许您覆盖
i和/或 @ 的值987654326@.
标签: c pointers segmentation-fault