blob: 13f0a8fc3e4d3404f3bd2888b710ac305ec93e04 [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;
Paul Sokolovsky02de0c52014-01-01 23:15:47 +02007static int current_bytes_allocated = 0;
Damien429d7192013-10-04 19:53:11 +01008
Damien429d7192013-10-04 19:53:11 +01009void *m_malloc(int num_bytes) {
10 if (num_bytes == 0) {
11 return NULL;
12 }
13 void *ptr = malloc(num_bytes);
14 if (ptr == NULL) {
15 printf("could not allocate memory, allocating %d bytes\n", num_bytes);
16 return NULL;
17 }
18 total_bytes_allocated += num_bytes;
Paul Sokolovsky02de0c52014-01-01 23:15:47 +020019 current_bytes_allocated += num_bytes;
Damien429d7192013-10-04 19:53:11 +010020 return ptr;
21}
22
23void *m_malloc0(int num_bytes) {
24 if (num_bytes == 0) {
25 return NULL;
26 }
27 void *ptr = calloc(1, num_bytes);
28 if (ptr == NULL) {
29 printf("could not allocate memory, allocating %d bytes\n", num_bytes);
30 return NULL;
31 }
32 total_bytes_allocated += num_bytes;
Paul Sokolovsky02de0c52014-01-01 23:15:47 +020033 current_bytes_allocated += num_bytes;
Damien429d7192013-10-04 19:53:11 +010034 return ptr;
35}
36
Damien732407f2013-12-29 19:33:23 +000037void *m_realloc(void *ptr, int old_num_bytes, int new_num_bytes) {
38 if (new_num_bytes == 0) {
Damien429d7192013-10-04 19:53:11 +010039 free(ptr);
40 return NULL;
41 }
Damien732407f2013-12-29 19:33:23 +000042 ptr = realloc(ptr, new_num_bytes);
Damien429d7192013-10-04 19:53:11 +010043 if (ptr == NULL) {
Damien732407f2013-12-29 19:33:23 +000044 printf("could not allocate memory, reallocating %d bytes\n", new_num_bytes);
Damien429d7192013-10-04 19:53:11 +010045 return NULL;
46 }
Paul Sokolovsky43f1c802014-01-01 23:04:25 +020047 // At first thought, "Total bytes allocated" should only grow,
48 // after all, it's *total*. But consider for example 2K block
49 // shrunk to 1K and then grown to 2K again. It's still 2K
50 // allocated total. If we process only positive increments,
51 // we'll count 3K.
Paul Sokolovsky02de0c52014-01-01 23:15:47 +020052 int diff = new_num_bytes - old_num_bytes;
53 total_bytes_allocated += diff;
54 current_bytes_allocated += diff;
Damien429d7192013-10-04 19:53:11 +010055 return ptr;
56}
57
Damien732407f2013-12-29 19:33:23 +000058void m_free(void *ptr, int num_bytes) {
59 if (ptr != NULL) {
60 free(ptr);
61 }
Paul Sokolovsky02de0c52014-01-01 23:15:47 +020062 current_bytes_allocated -= num_bytes;
Damien732407f2013-12-29 19:33:23 +000063}
64
Damien8b3a7c22013-10-23 20:20:17 +010065int m_get_total_bytes_allocated(void) {
Damien429d7192013-10-04 19:53:11 +010066 return total_bytes_allocated;
67}
Paul Sokolovsky02de0c52014-01-01 23:15:47 +020068
69int m_get_current_bytes_allocated(void) {
70 return current_bytes_allocated;
71}