Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is memory allocated during compilation?

When I write

int main()
{
    int j;
}

The memory for j is allocated at the time of compilation, but when during compilation?

What are the various stages of compilation when memory is allotted to a variable?

What if j were global?

like image 617
TwiggedToday Avatar asked Jul 24 '26 05:07

TwiggedToday


2 Answers

I guess you are mixing things up.

Compiler doesn't allocate memory for variables - it generates code that allocates memory for variables at runtime. For globals is will be added to program start-up code.

like image 132
qrdl Avatar answered Jul 27 '26 01:07

qrdl


In C, main is compiled the same as every other function: any variables declared in main will be "allocated" on the stack. A stack frame is the portion of the stack that is used by a single function call. The frame contains slots for all of the locals used within a function. This memory is considered temporary since when the function returns, this frame will be popped off the stack.

The C compiler will assign a static address to global variables. This address is considered part of the binary's "image" and as such has a static location in memory. The C compiler knows the size of every type, so it can set aside the appropriate amount of space in the memory layout of the binary for each global variable. Then, any code that accesses this variable will simply reference this address instead.

You can examine a variable's address with code like this:

#include<stdio.h>

int i;

void foo(int n)
{
    if(n > 2)
        return;

    printf("From foo &n = %xd\n", &n);
    printf("From foo &i = %xd\n", &i);

    foo(n+1);
}


int main()
{
    printf("&i = %xd\n", &i);
    foo(0);
    return 0;
}

Running this code produces output similar to:

./a.out 
&i = 600934d
From foo &n = 38bc4efcd
From foo &i = 600934d
From foo &n = 38bc4eccd
From foo &i = 600934d
From foo &n = 38bc4e9cd
From foo &i = 600934d

There are two things you should notice here:

  1. The address of i is constant every time it is referenced
  2. The address of n (a variable local to the function foo changes with each call to foo. In fact, it will decrease every time, since the stack grows downward.
like image 45
Doug Avatar answered Jul 27 '26 01:07

Doug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!