为什么编译器不给我错误?

why the compiler don't give me error?

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

int main() {
    system("clear");
    int *pt = malloc(2 * sizeof *pt);
    int *tmp = NULL;
    int i;

    pt[0] = 44;
    pt[1] = 9;
    printf("pt[0] : %d\n", pt[0]);
    printf("pt[1] : %d\n", pt[1]);
    tmp = realloc(pt, 3 * sizeof *pt);
    if (!tmp) {
        printf("merde alors\n");
    } else {
        pt = tmp;
        for (i = 0; i < 5; i++) {
            pt[i] = i + 1;
            printf("pt[%d] : %d\n", i, pt[i]);
        }
    }
    //the compiler should give me an error here, because I try use an unallocated memory:
    printf("pt[%d] : %d\n", i + 8, pt[i + 8]);
    free(pt);
    return 0;
}

大家好:) 我不明白,如您所见,我尝试使用未分配的内存,所以我希望从编译器收到一个严重的错误。 请原谅我糟糕的英语。 感谢您的时间 :) Valgrind report :

  //the compiler should give me an error here, because i try use an unallocated memory:   
  printf("pt[%d] : %d\n", i+8, pt[i+8]);

通常你不会从编译器中得到这样的错误,由你来跟踪它。这就是C的美好或阴暗面。如果出现这种问题undefined behaviour(UB),结果更糟。

所以这取决于你。当存在明显的数组越界访问时,某些编译器标志或静态分析器有时可能会帮助您。

许多其他相关问题也是如此,在这些问题上编译器不会警告您,您会得到 UB - 这就是为什么在 C 或 C++ 等语言中,您确实需要知道自己在做什么。

同样在这种特殊情况下,如果您在 运行 时指定数组大小,编译器甚至可能不知道数组大小是多少 - 因此它不会给您错误。即使它知道,编译器也不会总是告诉你数组越界访问。

编译器在编译时不会检查您访问的内存是否存在。这一切都是在运行时由您的操作系统完成的。导致段错误发生的不是 C 本身,而是您的操作系统实际上告诉 C 停止。