gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:15:20 24 4
gpt4 key购买 nike

#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 - 为什么编译器不给我错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35397717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com