堆栈是一个小的内存区域,在执行期间将临时值放入其中。与堆分配相比,将数据分配到堆栈中的速度非常快,因为已经为此分配了所有内存。

int main() {
    int a = 0; //Stored on the stack
    return a;
}

堆栈的命名是因为函数调用链将其临时内存堆叠在一起,每个内存使用一个单独的小部分内存。

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();
}

存储在堆栈中的数据仅在分配变量的作用域仍处于活动状态时才有效。

int* pA = nullptr;

void foo() {
    int b = *pA;
    pA = &b;
}

int main() {
    int a = 5;
    pA = &a;
    foo();
    //Undefined behavior, the value pointed to by pA is no longer in scope
    a = *pA;
}