Home > Software design >  C: how stack array with variable size works and result is correct? What happened in memory?
C: how stack array with variable size works and result is correct? What happened in memory?

Time:08-20

I am confused why following code works and result is correct,

int size = 5;
int array[size];

I remember that stack array CANNOT assign its size by variable(except const), because variable only know when runtime. This code shall report compiler error. However, today, I face this kind of code at work, I use -std=c89, and c99, etc, no any problem.

I assign 5 values to it, works. I assign 6 values to it, works(No seg fault). I assign 100 values to it, end part(out of range) gets wrong value, remaining still correct.

I am not sure 1. Why this can compile? gcc changed? or it always can compile this? 2. Why this work? Stack array is not allocated at runtime time, its size is fixed, why this "pseudo-dynamic" array works? Thanks

CodePudding user response:

I remember that stack array CANNOT assign its size by variable(except const), because variable only know when runtime.

This is false. A static array cannot have a variable length, since its length must be fixed during translation time (compilation time). An automatic array can have a variable length (subject to compiler support), since it is commonly implemented by using the hardware stack, which is designed to support run-time allocations.

However, today, I face this kind of code at work, I use -std=c89, and c99, etc, no any problem.

Support for variable-length arrays was required in C 1999. Compilers earlier than that may have supported it as an extension. It was made an optional feature in later versions of the standard, but compilers that had support previously generally retained it.

This code shall report compiler error.

Are you saying there is a rule that the compiler shall report an error for this? What rule, why do you say that?

I assign 5 values to it, works. I assign 6 values to it, works(No seg fault). I assign 100 values to it, end part(out of range) gets wrong value, remaining still correct.

When you use more elements than have been allocated for an array, the behavior is not defined by the C standard or, generally, but an implementation (except when using debugging or safety features to detect or avoid overruns). Commonly, there is nothing to prevent you from trying to use six or more elements of a five-element array. Doing so may corrupt your program’s memory in various ways. It may appear to work in some circumstances, as long as the overrun does not destroy other data your program needs to appear to work.

I am not sure 1. Why this can compile? gcc changed?

It compiled because the compiler supported variable length arrays.

  1. Why this work? Stack array is not allocated at runtime time, its size is fixed, why this "pseudo-dynamic" array works?

Stack arrays are generally allocated at run time.

  •  Tags:  
  • c gcc
  • Related