Stack
suggest changeThe stack is a region of memory into which automatic variables are placed during execution. Allocating them is very fast compared to heap allocation, as that memory has already been reserved for this purpose.
int main() {
int a = 0; //Stored on the stack
return a;
}
The stack is named because chains of function calls will have their temporary memory ‘stacked’ on top of each other, each one using a separate small section of memory.
float bar() {
//f will be placed on the stack after anything else
float f = 2;
return f;
}
double foo() {
//d will be placed just after anything within main()
double d = bar();
return d;
}
int main() {
//The stack has no user variables stored in it until foo() is called
return (int)foo();
}
Data stored on the stack is only valid so long as the scope that allocated the variable is still active.
int* pA = nullptr;
void foo() {
int b = *pA;
pA = &b;
}
int main() {
int a = 5;
pA = &a;
foo();
//Undefined behavior: b's lifetime has ended
a = *pA;
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents