0

When I run this code:

#include <stdio.h>

int main() {

    int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int y[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};

    int t;

    for (t = 0 ; t < 22 ;t++){
        printf( "%d\t\n", x[t]);
    }

    return 0;
}

for some reason, C is concatenating the y array onto the x array. Could somebody please explain why it is doing that? Thanks.

2
  • it's not concatenating it, it's just stored afterwards, your counter is going too high. Commented Nov 1, 2015 at 0:48
  • @maraca So why the random integer afterwards? I get the output 1 2 3 4 5 6 7 8 9 10 4195917 0 2 4... Commented Nov 1, 2015 at 2:28

3 Answers 3

3

Your compiler placed the two arrays next to each other in the static data area of your program. Because they're both composed of 4-byte values they're aligned on an x86 word boundary so there will be no padding between them.

This behaviour is not guaranteed, your code is relying on undefined behaviour: exceeding the bounds of an array.

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

Comments

2

Even if it happens to work this way, you are accessing an array out of its bounds, so you have Undefined Behavior (UB).

UB can take any form, and here it just happens that way, (simply because the arrays are next to each other in memory, but you should not count on that).

2 Comments

So why the random integer afterwards? I get the output 1 2 3 4 5 6 7 8 9 10 4195917 0 2 4...
@Plinth Some gap between the two arrays, non-initialized, simply. UB is UB. Take another compiler or another platform and you might find a different behavior resulting from the same error. That is why we should not lose much time to analyze UB.
0

When the memory is allocated for the two arrays, they happen to be placed on the stack in contiguous memory locations. There is no guarantee that they will be arranged that way, but in this case they were.

During the build process, the compiler and/or linker decide where in memory variables will be placed. In a simple program like this, there's a good chance variables of the same type that are declared one right after the other will be placed next to one another in memory.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.