Graphics Programs Reference
In-Depth Information
int global_initialized_var = 5;
void function() { // This is just a demo function.
int stack_var; // Notice this variable has the same name as the one in main().
printf("the function's stack_var is at address 0x%08x\n", &stack_var);
}
int main() {
int stack_var; // Same name as the variable in function()
static int static_initialized_var = 5;
static int static_var;
int *heap_var_ptr;
heap_var_ptr = (int *) malloc(4);
// These variables are in the 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 variables are in the bss segment.
printf("static_var is at address 0x%08x\n", &static_var);
printf("global_var is at address 0x%08x\n\n", &global_var);
// This variable is in the heap segment.
printf("heap_var is at address 0x%08x\n\n", heap_var_ptr);
// These variables are in the stack segment.
printf("stack_var is at address 0x%08x\n", &stack_var);
function();
}
Most of this code is fairly self-explanatory because of the descriptive
variable names. The global and static variables are declared as described
earlier, and initialized counterparts are also declared. The stack variable is
declared both in main() and in function() to showcase the effect of functional
contexts. The heap variable is actually declared as an integer pointer, which
will point to memory allocated on the heap memory segment. The malloc()
function is called to allocate four bytes on the heap. Since the newly allocated
memory could be of any data type, the malloc() function returns a void
pointer, which needs to be typecast into an integer pointer.
reader@hacking:~/booksrc $ gcc memory_segments.c
reader@hacking:~/booksrc $ ./a.out
global_initialized_var is at address 0x080497ec
static_initialized_var is at address 0x080497f0
static_var is at address 0x080497f8
global_var is at address 0x080497fc
heap_var is at address 0x0804a008
Search WWH ::




Custom Search