aiao aiao - 1 month ago 10
C Question

Array of runtime size and frame size deduction

Code:

#include <stdio.h>

int main() {

int size;
scanf("%d", &size);
int foo[size];

for(int i = 0; i < size; i++)
scanf("%d", &foo[i]);

for(int i = 0; i < size; i++)
printf("%d\n",foo[i]);

return 0;
}


How does this code compile? More specifically: how does the compiler know what is the size of frame
main
if size of local variable
foo
is not known at compile time. I was expecting a compile error along the lines: "
foo
has incomplete type"

To have also tried the code and it also runs fine:

Answer Source

In your code, you will first read data to specify size of array elements and then it will allocate that array on stack.

This approach is available from C99.

How compiler knows the size? It doesn't know. if you will enter too big value for size you may get stack overflow.

It will compile in a way that it will make sure to create as big push as required to put entire array to stack according to variable of size multiplied by size of single array element:

stack_size_usage = size * sizeof (int)

In C89, this would reproduce error as all variables must be first initialized before any code can be executed.


I would instead use HEAP memory for this type of allocation.

#include <stdio.h>

int main() {
    int size;
    int* foo;
    scanf("%d", &size);

    foo = malloc(sizeof(*foo) * size);
    if (!foo) { /* failed, stop program */ }

    for(int i = 0; i < size; i++)
        scanf("%d", &foo[i]);

    for(int i = 0; i < size; i++)
        printf("%d\n",foo[i]);

    free(foo);
    return 0;
}