-
Notifications
You must be signed in to change notification settings - Fork 51
/
memutil.c
68 lines (51 loc) · 1.22 KB
/
memutil.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "err.h"
#include "memutil.h"
/**
* Wrapper for malloc that prints an error message and exits
* if memory could not be allocated
*/
void *my_malloc(size_t n_bytes) {
void *mem;
mem = malloc(n_bytes);
if(!mem) {
my_err("%s:%d: could not allocate %ld bytes of memory\n",
__FILE__, __LINE__, n_bytes);
}
return mem;
}
/**
* Wrapper for malloc that allocates memory and
* then sets every byte to 0 (NULL).
*/
void *my_malloc0(size_t n_bytes) {
void *mem;
mem = my_malloc(n_bytes);
memset(mem, 0, n_bytes);
return mem;
}
/**
* Wrapper for realloc that prints an error message and exits
* if memory could not be allocated
*/
void *my_realloc(void *ptr, size_t n_bytes) {
ptr = realloc(ptr, n_bytes);
if(!ptr) {
my_err("%s:%d: could not allocate %ld bytes of memory\n",
__FILE__, __LINE__, n_bytes);
}
return ptr;
}
/**
* Wrapper around free that checks that provided
* ptr is not NULL before calling free
*/
void __MY_FREE(void *ptr, const char *filename, const int line_num) {
if(ptr == NULL) {
my_err("%s:%d: attempt to free NULL ptr at: %s:%d\n",
__FILE__, __LINE__, filename, line_num);
}
free(ptr);
}