关于指针和分段错误

About pointers and segmentation fault

所以,我有这个代码:

#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

不明白为什么会这样,看起来我没有增加

in this way it goes in segmentation fault as it supposed to be

这不是“应该”做任何特别的事情。当 i >= sizeof(int) 未定义的行为 时,您使用 p[i] 做什么,真的什么都可能发生。

Uncommenting this line of code above there: p[i] = 0; it doesn't go in segmentation fault

它仍然是未定义的行为。它没有以分段错误结束的事实并不意味着什么。我只能 猜测 p[i] = 0 在某些时候最终会用 0 覆盖 i 的值,因此你最终会无限循环。

Can't understand why this happens

试图理解未定义的行为没有多大意义。没有合理的解释,只能猜测。


如果您想讨论给定您的程序的特定编译器生成的程序集,那么我们当然可以讨论它并告诉您事情发生的确切原因,但是给定您的 C 源代码,任何东西都可以发生。未定义的行为就是未定义的行为。