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