根据本文内容
http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html#sec-6
A key to understanding the stack is the notion that when a function exits, all of its variables are popped off of the stack (and hence lost forever). Thus stack variables are local in nature.
因此,堆栈中属于该函数的所有变量都将被弹出,除了返回到函数的值(或者可能为父函数重新分配?),或者它不是静态的。
但是这个特定的程序运行得很好。
#include<stdio.h>
int* func()
{
int a=6;
int *b;
b=&a;
printf("in func - %d \n",*b);
return b;
}
void func2()
{
int a,c;
a=99;
c=2*a;
printf("in func 2 - %d \n",c);
}
void main()
{
int *b;
b=func();
func2();
printf("in main - %d",*b);
}
输出:
C:\Users\Shaurya\Desktop>gcc asw.c
C:\Users\Shaurya\Desktop>a
in func - 6
in func 2 - 198
in main - 6
C:\Users\Shaurya\Desktop>
我认为用户分配的变量(使用 calloc、malloc、realloc)可以被其他函数访问,因为它们位于堆中,正如文章所述。 但是,如果我们创建一个指向堆栈中的局部变量的指针,并返回该指针,那么该变量也可以在其他函数中访问。
最佳答案
通过返回局部变量的地址(并尝试在调用者中取消引用它),您的程序会调用未定义的行为。未定义行为的一种可能结果是您的程序似乎运行正常。但是,如果您更改代码以在调用 func
和 printf
之间调用另一个函数(尤其是创建和设置局部变量的函数),您可能会得到一个不同的结果。
a
曾经占据的内存单元1 显然仍然存在,并且将包含 a
的最后一个值,直到其他东西覆盖它。您只是碰巧在其他任何东西到达之前访问了该存储单元。
关于c - 堆栈和堆中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26369047/