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

-4 c arrays malloc realloc

#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;
}
Run Code Online (Sandbox Code Playgroud)

大家好:)我不明白,正如你所见,我尝试使用未分配的内存,所以我希望从编译器收到一个积极的错误.原谅我糟糕的英语.谢谢你的时间:) Valgrind报告:

gio*_*gim 5

  //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]);
Run Code Online (Sandbox Code Playgroud)

通常,您不会从编译器中获得此类错误,您可以自行跟踪它.这是C的美丽或黑暗的一面.如果发生这种问题是未定义的行为(UB),其结果甚至更糟.

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

对于许多其他相关问题也是如此,编译器不会警告您并且您获得UB - 这就是为什么在C或C++等语言中,您真的需要知道自己在做什么.

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