2

I have the following piece of code:

#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();
}

I am getting back the following:

# ./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

It is supposed that the first 2 variables because they are initialized static and global should be in the .data segment where the other 2 static_var and global_var should be in .bss segment. The addresses that I am getting I think imply that both of them are in the same memory region. I would do a blind guess and I would say that this is the .bss segment.

Anyway the question is the following, am I right ?? And if I am how is it possible to find out where are the "limits" of these regions (bss, data, etc) or from where they are starting etc.

user3124171
  • 401
  • 2
  • 7
  • 19

1 Answers1

1

Assuming you are compiling with something like gcc memaddr.c -g -o memaddr, you can use objdump -h to display size and address of your sections:

$ 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
$

Also you can use objdump -t to display addresses and sections your symbols belong in:

$ 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
$

So we can see that the .data and .bss sections are fairly small and happen to lie next to each other, so it is not surprising the .data and .bss addresses are so close.

Digital Trauma
  • 15,475
  • 3
  • 51
  • 83