1

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 foois 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:

aiao
  • 4,621
  • 3
  • 25
  • 47

1 Answers1

3

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;
}
unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
  • Does this mean that during a function call the stack pointer is incremented twice? First time for the local variable size, and the second time incremented with `sizeof(foo[size])`? – aiao Jun 08 '17 at 13:06
  • Yes, it is in fact. Please check my second example. It is better to use it. – unalignedmemoryaccess Jun 08 '17 at 13:07