Search code examples
arrayscgccstatic

Are arrays treated as static data structures by gcc compiler or as dynamic?


I thought arrays were considered static data structures.

Then we executed this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int a[5] = {10,20,30,40,50};
  a[5] = 100;
  a[6] = 200;
  printf("Out of bounds %d, %d", a[5], a[6]);
  return 0;
}

This returns Out of bounds 100 200 and ends normally. WHY?

Why is 200 declared and returned normally if a[5] is static?

Everything is leading me to the conclusion that gcc treats arrays as dynamic data structures.

Am I right? What is going on?


Solution

  • Static arrays have a fixed size specified at compile-time, and Variable-Length arrays have a fixed size determined at runtime. The compiler does not perform bounds-checking on arrays at runtime.

    Your code has undefined behavior as you are accessing your array out of bounds, so literally anything can happen, including the code seemingly to work.

    The compiler does not resize an array dynamically at runtime when you access it out of bounds. You are simply corrupting surrounding memory by writing outside of the array. In your example, your code does not crash because it is accessing valid memory, but it is nonetheless memory that the array does not own.