段错误,执行所有代码行后程序崩溃

segmentation fault, Crashing the program after executing all lines of code

在此程序中:

#include <stdio.h>

int main(void)
{
    char ch = 'A';
    char* ptr = &ch;

    ptr[8] = 'B';
    printf("ptr[8] = %c\n", ptr[8]);

    *ptr = 'C';
    printf("*ptr = %c\n", *ptr);
}

输出:

ptr[8] = B
*ptr = C
Segmentation fault (core dumped)

我认为程序应该在 ptr[8] = 'B'; 行发生段错误并崩溃,但程序确实执行了其中的所有代码行然后崩溃了,这是我不明白的事情。

它不应该在第 ptr[8] = 'B'; 行崩溃并在那里停止执行吗?

通过写入 ptr[8],您可能会乱写任何调用 main 的函数的 return 地址,因此处理器试图跳转到一个奇怪的地方。 Core 不喜欢它并进行了大量转储。

为变量分配一些内存可能会有所帮助:

#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char ch = 'A';
    char *ptr;
    if (!( ptr = malloc(sizeof(char) * 100)))
        return 1;

    ptr[7] = ch;
    printf("ptr[8] = %c\n", ptr[7]);

    ptr[8] = 'B';
    printf("ptr[8] = %c\n", ptr[8]);

    *ptr = 'C';
    printf("*ptr = %c\n", *ptr);

    printf("*ptr = %c\n", ptr[0]);

    free(ptr);
}
(gdb) b main
Breakpoint 1 at 0x400535: file hello.c, line 5.
(gdb) r
Starting program: /home/sohil/a.out 

Breakpoint 1, main () at hello.c:5
5       char ch = 'A';
(gdb) c
Continuing.

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400551 in main () at hello.c:9
9       printf("ptr[8] = %c\n", ptr[8]);
(gdb) bt
#0  0x0000000000400551 in main () at hello.c:9
(gdb) 

你永远不会在 ptr[8] = 'C' 上遇到段错误,因为任何无效的内存写入,但是当你在 printf 中访问时,它会导致段错误,如 gdb 所示.