Graphics Programs Reference
In-Depth Information
This program accepts a command-line argument for the size of the first
memory allocation, with a default value of 50. Then it uses the malloc() and
free() functions to allocate and deallocate memory on the heap. There are
plenty of printf() statements to debug what is actually happening when the
program is executed. Since malloc() doesn't know what type of memory it's
allocating, it returns a void pointer to the newly allocated heap memory,
which must be typecast into the appropriate type. After every malloc() call,
there is an error-checking block that checks whether or not the allocation
failed. If the allocation fails and the pointer is NULL, fprintf() is used to
print an error message to standard error and the program exits. The fprintf()
function is very similar to printf() ; however, its first argument is stderr , which
is a standard filestream meant for displaying errors. This function will be
explained more later, but for now, it's just used as a way to properly display
an error. The rest of the program is pretty straightforward.
reader@hacking:~/booksrc $ gcc -o heap_example heap_example.c
reader@hacking:~/booksrc $ ./heap_example
[+] allocating 50 bytes of memory on the heap for char_ptr
char_ptr (0x804a008) --> 'This is memory is located on the heap.'
[+] allocating 12 bytes of memory on the heap for int_ptr
int_ptr (0x804a040) --> 31337
[-] freeing char_ptr's heap memory...
[+] allocating another 15 bytes for char_ptr
char_ptr (0x804a050) --> 'new memory'
[-] freeing int_ptr's heap memory...
[-] freeing char_ptr's heap memory...
reader@hacking:~/booksrc $
In the preceding output, notice that each block of memory has an incre-
mentally higher memory address in the heap. Even though the first 50 bytes
were deallocated, when 15 more bytes are requested, they are put after the
12 bytes allocated for the int_ptr . The heap allocation functions control this
behavior, which can be explored by changing the size of the initial memory
allocation.
reader@hacking:~/booksrc $ ./heap_example 100
[+] allocating 100 bytes of memory on the heap for char_ptr
char_ptr (0x804a008) --> 'This is memory is located on the heap.'
[+] allocating 12 bytes of memory on the heap for int_ptr
int_ptr (0x804a070) --> 31337
[-] freeing char_ptr's heap memory...
[+] allocating another 15 bytes for char_ptr
char_ptr (0x804a008) --> 'new memory'
[-] freeing int_ptr's heap memory...
[-] freeing char_ptr's heap memory...
r eader@hacking:~/booksrc $
If a larger block of memory is allocated and then deallocated, the final
15-byte allocation will occur in that freed memory space, instead. By experi-
menting with different values, you can figure out exactly when the allocation
Search WWH ::




Custom Search