Damien | 429d719 | 2013-10-04 19:53:11 +0100 | [diff] [blame] | 1 | #include <stdio.h> |
| 2 | #include <stdlib.h> |
| 3 | |
| 4 | #include "misc.h" |
| 5 | |
| 6 | static int total_bytes_allocated = 0; |
| 7 | |
Damien | 429d719 | 2013-10-04 19:53:11 +0100 | [diff] [blame] | 8 | void *m_malloc(int num_bytes) { |
| 9 | if (num_bytes == 0) { |
| 10 | return NULL; |
| 11 | } |
| 12 | void *ptr = malloc(num_bytes); |
| 13 | if (ptr == NULL) { |
| 14 | printf("could not allocate memory, allocating %d bytes\n", num_bytes); |
| 15 | return NULL; |
| 16 | } |
| 17 | total_bytes_allocated += num_bytes; |
| 18 | return ptr; |
| 19 | } |
| 20 | |
| 21 | void *m_malloc0(int num_bytes) { |
| 22 | if (num_bytes == 0) { |
| 23 | return NULL; |
| 24 | } |
| 25 | void *ptr = calloc(1, num_bytes); |
| 26 | if (ptr == NULL) { |
| 27 | printf("could not allocate memory, allocating %d bytes\n", num_bytes); |
| 28 | return NULL; |
| 29 | } |
| 30 | total_bytes_allocated += num_bytes; |
| 31 | return ptr; |
| 32 | } |
| 33 | |
Damien | 732407f | 2013-12-29 19:33:23 +0000 | [diff] [blame^] | 34 | void *m_realloc(void *ptr, int old_num_bytes, int new_num_bytes) { |
| 35 | if (new_num_bytes == 0) { |
Damien | 429d719 | 2013-10-04 19:53:11 +0100 | [diff] [blame] | 36 | free(ptr); |
| 37 | return NULL; |
| 38 | } |
Damien | 732407f | 2013-12-29 19:33:23 +0000 | [diff] [blame^] | 39 | ptr = realloc(ptr, new_num_bytes); |
Damien | 429d719 | 2013-10-04 19:53:11 +0100 | [diff] [blame] | 40 | if (ptr == NULL) { |
Damien | 732407f | 2013-12-29 19:33:23 +0000 | [diff] [blame^] | 41 | printf("could not allocate memory, reallocating %d bytes\n", new_num_bytes); |
Damien | 429d719 | 2013-10-04 19:53:11 +0100 | [diff] [blame] | 42 | return NULL; |
| 43 | } |
Damien | 732407f | 2013-12-29 19:33:23 +0000 | [diff] [blame^] | 44 | total_bytes_allocated += new_num_bytes; |
Damien | 429d719 | 2013-10-04 19:53:11 +0100 | [diff] [blame] | 45 | return ptr; |
| 46 | } |
| 47 | |
Damien | 732407f | 2013-12-29 19:33:23 +0000 | [diff] [blame^] | 48 | void m_free(void *ptr, int num_bytes) { |
| 49 | if (ptr != NULL) { |
| 50 | free(ptr); |
| 51 | } |
| 52 | } |
| 53 | |
Damien | 8b3a7c2 | 2013-10-23 20:20:17 +0100 | [diff] [blame] | 54 | int m_get_total_bytes_allocated(void) { |
Damien | 429d719 | 2013-10-04 19:53:11 +0100 | [diff] [blame] | 55 | return total_bytes_allocated; |
| 56 | } |