简体   繁体   中英

Does GCC check array bounds?

I wrote a C program as follows and compiled it using GCC version 4.6.3.

#include <stdio.h>

int main(void)
{
    char array1[7] = "network"; // no space for \0 in array here
    char array2[5] = "network"; // even here, no space for \0 in array

    printf("1. %s\n",array1);
    printf("2. %s\n",array2);
    return 0;
}

On compilation :-

warning: initializer-string for array of chars is too long [enabled by default]

the output of program is :-

1. network
2. netwo

In output for array2 :- netwo+unprintable character. The non-printable character having hex value 7F.

My question is:-

  • While printing value of array1, why doesn't it print garbage value after printing "network" as in case of printing array2.

This doubt is supported by the fact that there is no NULL terminator in array1 nor in array2, so why garbage value only after array2's output?

So, does GCC check array bounds?

It doesn't print garbage after network out of pure bad luck; there happens to be a zero byte around. You're invoking undefined behaviour, so any result is permitted.

C compilers do check for overlong initializers, but are explicitly obliged to allow the 'no terminating null' version (though they can still warn about it, but usually don't; GCC 4.7.1 does not).

For general array access, the compiler does not usually check array bounds, though you can sometimes get information from GCC 4.7.1 under some circumstances (lots of options required, including -O for optimization).

您正在利用未定义的行为,任何事情都可能发生。

When you initialize a char array with a too long string, you use undefined behavior. This means that anything can happen, even that the correct value appears.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM