blob: a94edd3fe9b33613d57ebdccdd3d40bf80393148 [file] [log] [blame]
Damien429d7192013-10-04 19:53:11 +01001#include <stdio.h>
2#include <stdlib.h>
3
4#include "misc.h"
5
6static int total_bytes_allocated = 0;
7
Damien429d7192013-10-04 19:53:11 +01008void *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
21void *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
Damien732407f2013-12-29 19:33:23 +000034void *m_realloc(void *ptr, int old_num_bytes, int new_num_bytes) {
35 if (new_num_bytes == 0) {
Damien429d7192013-10-04 19:53:11 +010036 free(ptr);
37 return NULL;
38 }
Damien732407f2013-12-29 19:33:23 +000039 ptr = realloc(ptr, new_num_bytes);
Damien429d7192013-10-04 19:53:11 +010040 if (ptr == NULL) {
Damien732407f2013-12-29 19:33:23 +000041 printf("could not allocate memory, reallocating %d bytes\n", new_num_bytes);
Damien429d7192013-10-04 19:53:11 +010042 return NULL;
43 }
Paul Sokolovsky43f1c802014-01-01 23:04:25 +020044 // At first thought, "Total bytes allocated" should only grow,
45 // after all, it's *total*. But consider for example 2K block
46 // shrunk to 1K and then grown to 2K again. It's still 2K
47 // allocated total. If we process only positive increments,
48 // we'll count 3K.
49 total_bytes_allocated += new_num_bytes - old_num_bytes;
Damien429d7192013-10-04 19:53:11 +010050 return ptr;
51}
52
Damien732407f2013-12-29 19:33:23 +000053void m_free(void *ptr, int num_bytes) {
54 if (ptr != NULL) {
55 free(ptr);
56 }
57}
58
Damien8b3a7c22013-10-23 20:20:17 +010059int m_get_total_bytes_allocated(void) {
Damien429d7192013-10-04 19:53:11 +010060 return total_bytes_allocated;
61}