Sam*_*aid 19 c memory-management heap-memory stack-memory dynamic-allocation
这似乎是一个非常基本的问题,但它一直在我脑海中:
当我们分配一个局部变量时,它会进入堆栈.类似地,动态分配会导致变量进入堆.现在,我的问题是,这个变量实际上是在堆栈还是堆上,或者我们只是堆栈和堆中的引用.
例如,
假设我声明了一个变量int i.现在这i是在堆栈上分配的.那么,当我打印地址时i,这将是堆栈中的一个位置?堆的问题也一样.
Chr*_*rle 52
我不完全确定你在问什么,但我会尽力回答.
以下是i在堆栈上声明一个变量:
int i;
Run Code Online (Sandbox Code Playgroud)
当我要求使用地址时,&i我得到堆栈上的实际位置.
当我使用动态分配内容时malloc,实际上存储了两个数据.动态内存在堆上分配,指针本身在堆栈上分配.所以在这段代码中:
int* j = malloc(sizeof(int));
Run Code Online (Sandbox Code Playgroud)
这是在堆上为整数分配空间.它还在堆栈上为指针(j)分配空间.变量j的值设置为返回的地址malloc.
Dar*_*rda 12
希望以下内容对您有所帮助:
void foo()
{
// an integer stored on the stack
int a_stack_integer;
// a pointer to integer data, the pointer itself is stored on the stack
int *a_stack_pointer;
// make a_stack_pointer "point" to integer data that's allocated on the heap
a_stack_pointer = (int*)malloc(10 * sizeof(int));
}
Run Code Online (Sandbox Code Playgroud)
在堆栈变量的情况下,变量本身(实际数据)存储在堆栈中.
在堆分配内存的情况下,底层数据始终存储在堆上.指向该存储器/数据的指针可以本地存储在堆栈上.
希望这可以帮助.
指针变量本身将驻留在堆栈上.指针指向的内存将驻留在堆上.
int *i = malloc(sizeof(int));
Run Code Online (Sandbox Code Playgroud)
i将驻留在堆栈上,我指向的实际内存*i将在堆上.