Igor Liferenko
Igor Liferenko

Reputation: 1569

How reading beyond end of buffer works in C?

Create this x.c test file:

int main(void)
{
  char x[2] = {3};
  return x[2];
}

Then run

gcc x.c; ./a.out; echo $?

Result is: 64.

Why 64?

Incidentally, why if we use

return x[1];

we get 0? Why the {3} did not initialize x[1] too?

Upvotes: 1

Views: 130

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

How reading beyond end of buffer works in C? and Why 64?

It does not "work", it's the result of undefined behaviour. There does not exist an array element at x[2].

we get 0? Why the {3} did not initialize x[1] too?

That said, a statement like

 char x[2] = {3};

creates an array x, with two elements, accessed by x[0] and x[1], and initializes x[0] to 3 and any remaining element to 0 (as per the rules of initialization where there are less number of initializer element that the array elements). So, that {3} does not initialize all the array elements to a value 3, rather it sets the value of the first element only.

Quoting C11, chapter 6.7.9/P21

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Upvotes: 6

Related Questions