1 | /* |
---|
2 | * $Id$ |
---|
3 | * |
---|
4 | * Code (c)2006 Bruno Cornec <bruno@mondorescue.org> |
---|
5 | * |
---|
6 | * Main file of mr_mem : a very small and simple |
---|
7 | * library for memory management |
---|
8 | * |
---|
9 | * Provided under the GPLv2 |
---|
10 | */ |
---|
11 | |
---|
12 | #include <stdio.h> |
---|
13 | #include <stdlib.h> |
---|
14 | |
---|
15 | #include "mr_err.h" |
---|
16 | #include "mr_msg.h" |
---|
17 | |
---|
18 | /* |
---|
19 | * Function that frees memory if necessary |
---|
20 | */ |
---|
21 | void mr_free(void *allocated) { |
---|
22 | |
---|
23 | /* free man pages says that if allocated is NULL |
---|
24 | * nothing happens |
---|
25 | */ |
---|
26 | free(allocated); |
---|
27 | allocated = NULL; |
---|
28 | } |
---|
29 | |
---|
30 | /* encapsulation function for malloc */ |
---|
31 | void *mr_malloc(size_t size) { |
---|
32 | |
---|
33 | void *ret; |
---|
34 | |
---|
35 | ret = malloc(size); |
---|
36 | if (ret == NULL) { |
---|
37 | mr_log_exit(-1,"Unable to alloc memory in mr_malloc\nExiting..."); |
---|
38 | } |
---|
39 | return(ret); |
---|
40 | } |
---|
41 | |
---|
42 | /* encapsulation function for getline */ |
---|
43 | void mr_getline(char **lineptr, size_t *n, FILE *stream) { |
---|
44 | |
---|
45 | ssize_t ret; |
---|
46 | |
---|
47 | ret = getline(lineptr,n,stream); |
---|
48 | if (ret == -1) { |
---|
49 | mr_log_exit(-1,"Unable to alloc memory in mr_getline\nExiting..."); |
---|
50 | } |
---|
51 | } |
---|
52 | |
---|
53 | /* encapsulation function for asprintf */ |
---|
54 | void mr_asprintf(char **strp, const char *fmt, va_list args) { |
---|
55 | |
---|
56 | int res = 0; |
---|
57 | |
---|
58 | res = vasprintf(strp, fmt, args); |
---|
59 | if (res == -1) { |
---|
60 | mr_log_exit(-1,"Unable to alloc memory in mr_asprintf\nExiting..."); |
---|
61 | } |
---|
62 | } |
---|
63 | |
---|
64 | /* |
---|
65 | * Function that properly allocates a string from another one |
---|
66 | * freeing it before in any case |
---|
67 | */ |
---|
68 | void mr_allocstr(char *alloc, const char *orig) { |
---|
69 | |
---|
70 | mr_free((void *)alloc); |
---|
71 | mr_asprintf(&alloc, orig); |
---|
72 | } |
---|