1

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?

3
  • 1
    Checking array bounds is not part of the language C, so the compiler is not obliged to do so. Commented Jan 14, 2013 at 8:01
  • 1
    Read Buffer overruns / out of bounds access and Undefined behavior Commented Jan 14, 2013 at 8:05
  • Thanks for valuable info Commented Jan 14, 2013 at 9:20

3 Answers 3

4

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).

Sign up to request clarification or add additional context in comments.

Comments

2

You are exploiting undefined behaviour, anything can happen.

Comments

1

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.

1 Comment

-1, that's not what's going on here. It's perfectly fine to initialize an n-character array with a string constant holding exactly n characters, the terminator that's normally implied is then suppressed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.