确定 C 中的变量堆栈或堆



假设我有这些变量和指针。如何确定哪个在堆栈或堆中?

     #include <stdio.h>
     #define SIZE 5

    int main( void ) {
    int *zLkr;                 
    int *aLkr= NULL;
    void *sLkr= NULL;
    int num, k;
    int a[SIZE] = { 1, 2, 3, 4, 5 };
    zLkr = a;
    }

所有变量都有自动作用域。它们来自"堆栈",因为一旦函数返回,变量就不再有效。

命名函数变量永远不能来自你的意思是"堆"。命名函数变量的内存始终与函数作用域(或声明变量的函数中最内层的块作用域)相关联。

变量可以分配一个由malloc()或类似的动态分配函数获得的值。然后,该变量指向"堆"中存在的对象。但是,命名指针变量本身不在"堆"中。

有时"堆栈"本身是动态分配的。例如对于线程。然后,用于分配在该线程中运行的函数局部变量的内存位于"堆"中。但是,变量本身仍然是自动的,因为一旦函数返回,它们就无效。

局部变量在堆栈上分配

int main(void)
{    
    int thisVariableIsOnTheStack;
    return 0;
}

中的变量通过内存中某处的 malloc 分配。 该内存可以返回到堆中,并由以后的 malloc 调用重用。

int main(void)
{
    char *thisVariableIsOnTheHeap = (char *) malloc(100);
    free (thisVariableIsOnTheHeap);
    return 0;
}

模块变量都不是。 它们在一个模块的内存中有一个常量地址。

void f1(void)
{
    /* This function doesn't see thisIsAModule */
}
int thisIsaModule = 3;
void f(void)
{
    thisIsaModule *= 2;
}
int main(void)
{
    return thisIsaModule;
}

全局变量都不是。 它们在内存中具有常量值,但可以跨模块引用。

extern int globalVariable;    /* This is set in some other module. */
int main(void)
{
    return globalVariable;
}

最新更新