[英]Why gcc in 64 bit ubuntu doesn't detect the following array overflow?
So my code is 所以我的代码是
#include <stdio.h>
#include <string.h>
int main()
{
const char *a="123456789abcdef";
char b[10];
int i=0;
while((b[i]=a[i])!='\0')
++i;
printf("%s, %d\n",b,strlen(b));
return 0;
}
The code exists a array overflow with array b, but when I compile it with gcc(version 4.6.3) in my system (64bit ubuntu 12.04 lts),it succeed. 该代码与数组b存在数组溢出,但是当我在系统(64位ubuntu 12.04 lts)中使用gcc(版本4.6.3)对其进行编译时,它会成功。
The output of this program is 123456789abcdef, 15 and 该程序的输出是123456789abcdef,15和
returns 0 means this program exits normally. 返回0表示该程序正常退出。
I don't know whether it's my compiler's problem or my system's, is there anyone can tell me? 我不知道是我的编译器问题还是系统的问题,有人可以告诉我吗? PS It seems like it only appears in 64-bit linux with gcc. PS似乎它仅出现在带有gcc的64位linux中。 Is this a bug? 这是错误吗?
Array accesses are not checked in C. If you overflow a buffer like this, the result is undefined behavior. 在C中不检查数组访问。如果您这样溢出缓冲区,则结果是未定义的行为。 It is the programmer's responsibility to guard against this, not the compiler's. 防止这种情况的发生是程序员的责任,而不是编译器的责任。
There are tools though to assist in checking for invalid memory access. 虽然有一些工具可以帮助检查无效的内存访问。 Like Valgrind for doing so at runtime, and Clang's static analyzer for compile-time checking. 就像Valgrind在运行时这样做一样,而Clang的静态分析器则用于编译时检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.