1

I am not able to understand how variable size array works , whether memory for it is allocated on stack or somewhere else and how information about its size is obtained.

i tried the following code

#include<stdio.h>

int main()
{
    int n;
    scanf("%d",&n);

    int arr[n];

    printf("%d\n",sizeof(arr));

    return 0;
}

i mean i memory is allocted on stack ,then before running this function the stack frame is to be allocated and memory for local variables has to be allocated ,but the size of array is known after the function calls scanf().

2 Answers 2

2

On most contemporary systems with memory protection and so on, you can just grow the stack. If accessing the grown stack causes accesses to memory which is actually outside the valid range of virtual memory for the process, the operating system will catch that and map some more memory your way.

So there's no problem in doing that "on the fly", and of course "allocating n bytes on the stack" is generally about as complex as "stackpointer -= n".

There might be some additional complexity if the function has many exit paths, since they need to unwind the proper amount of stack depending on wether the variable-length array has been allocated or not, not sure how that is generally solved. That would be an easy code-reading exercise to find out.

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

Comments

2

In C++, this isn't (yet) allowed, although some compilers allow it as a non-standard extension. Dynamically-sized arrays, similar to those in C, are due to be introduced in C++14.

How to implement this is up to the compiler writer, as long as the memory is allocated somewhere and freed automatically. This is typically done by extending the stack frame once the size is known. There may or may not be a check that the stack is large enough, so beware creating large arrays like this.

Comments

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.