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 | #include <stdarg.h>
|
---|
15 |
|
---|
16 | #include "mr_err.h"
|
---|
17 | #include "mr_msg.h"
|
---|
18 |
|
---|
19 | /*
|
---|
20 | * Function that frees memory if necessary
|
---|
21 | */
|
---|
22 | void mr_free(void *allocated) {
|
---|
23 |
|
---|
24 | /* free man pages says that if allocated is NULL
|
---|
25 | * nothing happens
|
---|
26 | */
|
---|
27 | free(allocated);
|
---|
28 | allocated = NULL;
|
---|
29 | }
|
---|
30 |
|
---|
31 | /* encapsulation function for malloc */
|
---|
32 | void *mr_malloc(size_t size) {
|
---|
33 |
|
---|
34 | void *ret;
|
---|
35 |
|
---|
36 | ret = malloc(size);
|
---|
37 | if (ret == NULL) {
|
---|
38 | mr_log_exit(-1,"Unable to alloc memory in mr_malloc\nExiting...");
|
---|
39 | }
|
---|
40 | return(ret);
|
---|
41 | }
|
---|
42 |
|
---|
43 | /* encapsulation function for getline */
|
---|
44 | void mr_getline(char **lineptr, size_t *n, FILE *stream) {
|
---|
45 |
|
---|
46 | ssize_t ret;
|
---|
47 |
|
---|
48 | ret = getline(lineptr,n,stream);
|
---|
49 | if (ret == -1) {
|
---|
50 | mr_log_exit(-1,"Unable to alloc memory in mr_getline\nExiting...");
|
---|
51 | }
|
---|
52 | }
|
---|
53 |
|
---|
54 | /* encapsulation function for asprintf */
|
---|
55 | void mr_asprintf(char **strp, const char *fmt, ...) {
|
---|
56 |
|
---|
57 | va_list args;
|
---|
58 | int res = 0;
|
---|
59 |
|
---|
60 | va_start(args, fmt);
|
---|
61 | res = vasprintf(strp, fmt, args);
|
---|
62 | if (res == -1) {
|
---|
63 | mr_log_exit(-1,"Unable to alloc memory in mr_asprintf\nExiting...");
|
---|
64 | }
|
---|
65 | va_end(args);
|
---|
66 | }
|
---|
67 |
|
---|
68 | /*
|
---|
69 | * Function that properly allocates a string from another one
|
---|
70 | * freeing it before in any case
|
---|
71 | */
|
---|
72 | void mr_allocstr(char *alloc, const char *orig) {
|
---|
73 |
|
---|
74 | mr_free((void *)alloc);
|
---|
75 | mr_asprintf(&alloc, orig);
|
---|
76 | }
|
---|