2013-12-22 138 views
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,數據等)的「限制」或從哪裏開始等等。

+1

兩個挑剔 - 不要施放malloc()的結果http://stackoverflow.com/a/605858/2113226。並記住'免費(heap_var_ptr)' –

+0

你是非常正確的軌道上。 –

回答

1

假設你正在編譯類似gcc memaddr.c -g -o memaddr之類的東西,你可以使用objdump -h以顯示部分的大小和地址:

 
$ objdump -h memaddr | grep -e 'Size' -e '\.data' -e '\.bss' 
Idx Name   Size  VMA    LMA    File off Algn 
23 .data   00000018 0000000000601018 0000000000601018 00001018 2**3 
24 .bss   00000018 0000000000601030 0000000000601030 00001030 2**3 
$ 

您也可以使用objdump -t來顯示你的符號屬於地址和部分:

 
$ objdump -t memaddr | grep "_var" 
000000000060102c l  O .data 0000000000000004    static_initialized_var.2049 
0000000000601040 l  O .bss 0000000000000004    static_var.2050 
0000000000601044 g  O .bss 0000000000000004    global_var 
0000000000601028 g  O .data 0000000000000004    global_initialized_var 
$ 

因此,我們可以看到。數據和。 BSS部分相當小,恰好彼此相鄰,所以.data和.bss地址非常接近並不奇怪。