Graphics Programs Reference
In-Depth Information
stack_var is at address 0xbffff834
the function's stack_var is at address 0xbffff814
r eader@hacking:~/booksrc $
The first two initialized variables have the lowest memory addresses,
since they are located in the data memory segment. The next two variables,
static_var and global_var , are stored in the bss memory segment, since they
aren't initialized. These memory addresses are slightly larger than the previous
variables' addresses, since the bss segment is located below the data segment.
Since both of these memory segments have a fixed size after compilation,
there is little wasted space, and the addresses aren't very far apart.
The heap variable is stored in space allocated on the heap segment,
which is located just below the bss segment. Remember that memory in this
segment isn't fixed, and more space can be dynamically allocated later. Finally,
the last two stack_var s have very large memory addresses, since they are located
in the stack segment. Memory in the stack isn't fixed, either; however, this
memory starts at the bottom and grows backward toward the heap segment.
This allows both memory segments to be dynamic without wasting space in
memory. The first stack_var in the main() function's context is stored in the
stack segment within a stack frame. The second stack_var in function() has its
own unique context, so that variable is stored within a different stack frame
in the stack segment. When function() is called near the end of the program,
a new stack frame is created to store (among other things) the stack_var for
function() 's context. Since the stack grows back up toward the heap segment
with each new stack frame, the memory address for the second stack_var
( 0xbffff814 ) is smaller than the address for the first stack_var ( 0xbffff834 )
found within main() 's context.
0x272
Using the Heap
Using the other memory segments is simply a matter of how you declare
variables. However, using the heap requires a bit more effort. As previously
demonstrated, allocating memory on the heap is done using the malloc()
function. This function accepts a size as its only argument and reserves that
much space in the heap segment, returning the address to the start of this
memory as a void pointer. If the malloc() function can't allocate memory
for some reason, it will simply return a NULL pointer with a value of 0.
The corresponding deallocation function is free() . This function accepts a
pointer as its only argument and frees that memory space on the heap so it
can be used again later. These relatively simple functions are demonstrated
in heap_example.c.
heap_example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Search WWH ::




Custom Search