4

How compiler determine the size of below array at compile time?

int n;
scanf("%d",&n);
int a[n];

How it is different from dynamic allocation(other than memory is allocated in heap for dynamic array).

If possible please, explain this in terms of activation stack memory image how this array is allocated memory.

2 Answers 2

9

The array's size isn't determined at compile time; it's determined at run time. At the time that the array is allocated, n has a known value. In typical implementations where automatic variables are allocated on the program stack, the stack pointer will be adjusted to make room for that many ints. It becomes parts of the stack frame and will be automatically reclaimed when it goes out of scope.

This code was not valid in C90; C90 required that all variables be declared at the beginning of the block, so mixing declarations and code like this was not permitted. Variable-length arrays and mixed code and declarations were introduced in C99.

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

2 Comments

Excuse me but the fact that sizeof operator provides the size of the whole array for non Variable-Length Arrays, makes me think that this is only true for Variable-Length Arrays.
@ThoAppelsin: sizeof is special for variable-length arrays.
1

In C the proper name for the allocation type is automatic. In computing jargon the term stack is sometimes used synonymously.

The storage of a is valid from the point of definition int a[n]; up until the end of the enclosing scope (i.e. the end of the current function, or earlier).

It is just the same as int a[50]; , except that a different number of ints than 50 may be allocated.

A drawback of using automatic arrays (with or without runtime sizes) is that there is no portable way to protect against stack overflow. (Actually, stack overflow from automatic variables is something the C standard does not address at all, but it is a real problem in practice).

If you were to use dynamic allocation (i.e. malloc and friends) then it will let you know if there is insufficient memory by returning NULL, whereas stack overflows are nasty.

1 Comment

That's true. But it's still tidier (and typically has more space available before running into that) than stack overflow.

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.