diff options
| author | mo khan <mo@mokhan.ca> | 2014-07-22 21:19:29 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2014-07-22 21:19:29 -0600 |
| commit | 978cf6f2740be51428b41309c49dc91a8254ed96 (patch) | |
| tree | 07a9eab93f8d6b98a337f5e202b24b71146194b9 | |
| parent | 29dadec5aa24f2559734f2843d0c89c94318fb28 (diff) | |
heap example with malloc extracted to a function with error checking.
| -rw-r--r-- | errorchecked_heap.c | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/errorchecked_heap.c b/errorchecked_heap.c new file mode 100644 index 0000000..c1339ea --- /dev/null +++ b/errorchecked_heap.c @@ -0,0 +1,56 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +void *errorchecked_malloc(unsigned int); + +int main(int argc, const char *argv[]) +{ + char *char_ptr; + int *int_ptr; + int mem_size; + + if (argc < 2) + mem_size = 50; + else + mem_size = atoi(argv[1]); + + printf("\t[+] allocating %d bytes of memory on the heap for char_ptr\n", mem_size); + char_ptr = (char *) errorchecked_malloc(mem_size); + + strcpy(char_ptr, "this memory is located on the heap."); + printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr); + + printf("\t[+] allocating 12 bytes of memory on the heap for int_ptr\n"); + int_ptr = (int *) errorchecked_malloc(12); + + *int_ptr = 31337; + printf("int_ptr (%p) --> %d\n", int_ptr, *int_ptr); + + printf("\t[-] freeing char_ptr's heap memory...\n"); + free(char_ptr); + + printf("\t[+] allocating another 15 bytes for char_ptr\n"); + char_ptr = (char *)errorchecked_malloc(15); + + strcpy(char_ptr, "new memory"); + printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr); + + printf("\t[-] freeing int_ptr's heap memory...\n"); + free(int_ptr); + printf("\t[-] freeing char_ptr's heap memory...\n"); + free(char_ptr); + + return 0; +} + +void *errorchecked_malloc(unsigned int size) +{ + void *ptr; + ptr = malloc(size); + if (ptr == NULL) { + fprintf(stderr, "Error: could not allocate heap memory.\n"); + exit(-1); + } + return ptr; +} |
