Cocoo Wang
Cocoo Wang

Reputation: 9

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.

The output of this program is 123456789abcdef, 15 and
returns 0 means this program exits normally.

I don't know whether it's my compiler's problem or my system's, is there anyone can tell me? P.S. It seems like it only appears in 64-bit linux with gcc. Is this a bug?

Upvotes: 1

Views: 189

Answers (1)

Nikos C.
Nikos C.

Reputation: 51890

Array accesses are not checked in C. If you overflow a buffer like this, the result is undefined behavior. 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.

Upvotes: 7

Related Questions