Dioswison
Dioswison

Reputation: 119

How does declaring an array with a variable work inside a function

I am learning C and I realized that you can declare an array with the size determined by a function argument like in this example:

#include <stdio.h>

void foo(unsigned int size){
    int array[size];
    unsigned int i;
    
    for(i=0;i<size;i++){
        array[i]=i*2;
        printf("ArrayMember: %d\n",array[i]);
    }
}

int main(){  
    unsigned int a = 0;
    
    printf("Input a size\n");
    scanf("%u",&a);
    
    foo(a);

    return 0;
}

How is this memory assigned? I thought that compiler was the one reserving memory inside the stack, but the size is determined at runtime.

Does this memory get assigned inside the heap and then freed automatically?

Upvotes: 1

Views: 161

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 222302

How is this memory assigned? I thought that compiler was the one reserving memory inside the stack, but the size is determined at runtime.

For routines without variable-length arrays, the compiler generally changes the stack pointer by a fixed amount (by generating instructions to do that), thus reserving a fixed amount of memory.1

For a routine with a variable-length array, the compiler reserves a fixed amount of memory for the fixed purposes of the routine but also generates instructions to calculate the amount needed for the variable-length array and then change the stack pointer by that additional amount.

So, in both cases, the compiler is responsible for reserving memory, and it does so by generating instructions to change the stack pointer. Those instructions may use an amount calculated during compilation or may use an amount calculated during program execution.

Footnote

1 This can be done with an instruction that directly changes the stack pointer, such as a “subtract” instruction, or more complicated instructions, such as a “push” instruction that both decrements the stack pointer and writes a value to the stack.

Upvotes: 1

dbush
dbush

Reputation: 223689

This is called a variable length array. Such arrays have their size determined at runtime, and like fixed-length arrays, their lifetime ends when the enclosing scope ends.

A variable length array is typically allocated on the stack, just like any other local variable.

This feature was added to C in the C99 specification. It is not officially part of C++, although some compilers may allow it as an extension.

Upvotes: 2

Related Questions