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?
The stack itself is statically allocated. Variables allocated in the stack come and go, as control flow enters and leaves their scope.