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

时间:2016-02-14 20:39:34

标签: 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;
}
大家好啊:) 我不明白,如你所见,我尝试使用未分配的内存,所以我希望从编译器收到一个积极的错误。 原谅我糟糕的英语。 感谢您的时间 :) Valgrind report :

2 个答案:

答案 0 :(得分: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]);

通常,您不会从编译器中获得此类错误,您可以自行跟踪它。那是C的美丽或黑暗的一面。如果发生undefined behaviour(UB)这样的问题,结果会更糟。

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

同样适用于许多其他相关问题,编译器没有警告你并且你得到UB - 这就是为什么在C或C ++这样的语言中,你真的需要知道你在做什么

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

答案 1 :(得分:0)

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

相关问题