Search code examples
cmemorystackheap-memorydynamic-memory-allocation

Do the C compilers preallocate every variable that exists in a program? Or do they allocate while the program is running?


For example, when I define a variable, like int x = 20; in a function that can possibly be called in main, does the compiler already allocates stack memory for that variable? 'Cause, as I said, it's a variable that may be called, but also may not be called and the program could possibly end and never call it.

I'm studying dynamic memory allocation and use cases of malloc and Ive been reading some stuff that led me to pure confusion lol


Solution

  • int x = 20; tells the compiler to use 20 for x. That's it. Note I didn't mention memory at all. In fact, the following two programs are 100% equivalent:

    printf( "%d\n", 20 );
    
    int x = 20;
    printf( "%d\n", x );
    

    As long as it prints 20␊, the details of how it does it are not defined.


    But let's say it does create a variable on the stack.

    does the compiler already allocates stack memory for that variable?

    No. The whole point of using a stack is to provide temporary memory. And to allow recursion.