2
我已在下面的代碼段:存儲器分配和堆棧
#include <stdio.h>
int global_var;
int global_initialized_var=5;
void function(){
int stack_var;
printf("The function's stack_var is at address 0x%08x\n", &stack_var);
}
int main(){
int stack_var;
static int static_initialized_var = 5;
static int static_var;
int *heap_var_ptr;
heap_var_ptr = (int *) malloc(4);
// Next variables will be at data segment
printf("global_initialized_var is at address 0x%08x\n", &global_initialized_var);
printf("static_initialized_var is at address 0x%08x\n\n", &static_initialized_var);
// These will be in the bss segment
printf("static_var is at address 0x%08x\n", &static_var);
printf("global_var is at address 0x%08x\n", &global_var);
// This will be in heap segment
printf("heap_var is at address 0x%08x\n\n", heap_var_ptr);
// These will be in stack segment
printf("stack_var is at address 0x%08x\n", &stack_var);
function();
}
我正在回以下:
# ./memory_segments
global_initialized_var is at address 0x0804a018
static_initialized_var is at address 0x0804a01c
static_var is at address 0x0804a028
global_var is at address 0x0804a02c
heap_var is at address 0x09285008
stack_var is at address 0xbf809fbc
The function's stack_var is at address 0xbf809f8c
據推測,所述第一2個變量因爲它們初始化爲靜態,全局應該在.data段中,其他static_var和global_var應該位於.bss段中。我得到的地址我認爲暗示它們都在同一個內存區域。我會做一個盲目的猜測,我會說這是.bss段。
無論如何,問題是以下,我是嗎?如果我是怎麼可能找出這些區域(bss,數據等)的「限制」或從哪裏開始等等。
兩個挑剔 - 不要施放malloc()的結果http://stackoverflow.com/a/605858/2113226。並記住'免費(heap_var_ptr)' –
你是非常正確的軌道上。 –