random_stuff
random_stuff

Reputation: 337

Are variables on the stack "statically allocated"?

I was reading this article and saw this: "This article assumes that you already know and understand at least basically how the memory map in GNU/Linux system works, and specially the difference between memory statically allocated in the stack and memory dynamically allocated in the heap."

This confused me because I thought that stack and heap are dynamically allocated, meaning only allocated if necessary, and global variables and variables declared as "static" inside of a function are statically allocated, meaning always allocated.

For example, if I have

void f() {
    int x = 1;
    ...
}

the value 1 only gets put on the stack and the stack pointer only gets incremented if the function f() gets called. Likewise, if I have

void f() {
    int x = malloc(1 * sizeof(int));
    ...
}

that heap memory only gets allocated if f() is called. However, if I have "int x = 1;" in the global section of the program or "static int x = 1;" within a function body, any time I run this program, that memory will be allocated in the data section with the value 1.

Am I wrong about any of this?

Upvotes: 5

Views: 2212

Answers (2)

Eric
Eric

Reputation: 24890

Stack is allocated in unit of stack frame.

  • When a function is called, a stack frame is allocated for it,
  • When a function returns, its stack frame disappear,

And, stack helps to store function arguments & local variables.

After a function get its stack frame, yes, within the stack frame the function use bytes of it as need dynamic.


Dynamic allocate stack like heap

If u want to allocate memory on stack like the way as heap, then you can use alloca() from <alloca.h>, it's quicker than heap, but in most case u don't need that, it has disadvantages, thus not suggested in general case.


Describe stack allocation in different context might make it more clear:

  • From the view of a linux thread, (by the way, each process has 1 thread on creation by default, as main thread), the stack is of fix size & allocated on thread creation, (2Mb for IA-32, 32Mb for IA-64, by default), and you can change the default size as need. So you can say this is fix, and static.
  • From the view of a function within thread or process, the stack frame is allocated for it from the thread's stack memory when the function starts, and the stack frame disappear when the function finish.
  • From the view of a non-static local variable inside a function, the variable is allocated from the stack frame of the function as need, dynamically.

So, should it be called static or dynamical, you decide.

Upvotes: 2

rici
rici

Reputation: 241721

The stack itself is statically allocated. Variables allocated in the stack come and go, as control flow enters and leaves their scope.

Upvotes: 4

Related Questions