Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is memory allocated to local variables in C

As local variables are also called automatic variables, and are supposed to be allocated memory at run time, when function is accessed.

int main(){
    int a; // declaration 
    return 0;
}

int main(){
    int a[]; // compilation error, array_size missing
    return 0;
}

int main(){
    int a[2]; // declaration, but can't work without array_size, 
              // so at compile time it is checked!
    return 0;
}

My question is whether it's just a rule to give array_size in declaration in C, or memory is allocated at compile time for array (still local variable)

How does it work?

An array is a variable as per C programming by K&R. pg no 161.

like image 591
linuxD Avatar asked Mar 13 '13 12:03

linuxD


1 Answers

When you declare local variable, the size of it is known at a compile time, but memory allocation occurs during execution time.

So in your examples, array without a size is clearly a problem to compiler, as it doesn't know what is the size to include into assembler code.

If you don't know the size of an array, you can always use pointer types and malloc/free or even alloca. The first two operate on heap, and alloca actually uses stack.

The notable exception is static variables. The storage for them is allocated at a compile/link time already and can't be changed at runtime.

Examples:

int main(int argc, const char *argv[])
{
    int a; // a is a sizeof(int) allocated on stack
}

int main(int argc, const char *argv[])
{
    int a[2]; // a is a sizeof(int)*2 allocated on stack
}

int main(int argc, const char *argv[])
{
    int *a; // a is a sizeof(int*) allocated on stack (pointer)
    a = alloca(sizeof(int)*4); // a points to an area with size of 4 integers
                               // data is allocated on stack
}

int main(int argc, const char *argv[])
{
    static int a; // a is allocated in data segment, keeps the value
}
like image 82
Valeri Atamaniouk Avatar answered Oct 12 '22 23:10

Valeri Atamaniouk