source: trunk/mondo/src/lib/mr_mem.c @ 900

Last change on this file since 900 was 900, checked in by Bruno Cornec, 14 years ago

Huge patch to introduce low level functions that will bw used everywhere (mr_free, mr_asprintf, ...)
Nearly linking now due to that.

  • Property svn:eol-style set to native
File size: 1.7 KB
RevLine 
[900]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 */
22void 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 */
32void *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}
41
42/* encapsulation function for getline */
43void 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
54/* encapsulation function for vasprintf */
55void mr_vasprintf(char **strp, const char *fmt, va_list ap) {
56
57    int res = 0;
58    va_list args;
59
60    res = vasprintf(strp, fmt, ap);
61    if (res == -1) {
62        mr_log_exit(-1,"Unable to alloc memory in mr_vasprintf\nExiting...");
63    }
64}
65
66/* encapsulation function for asprintf */
67void mr_asprintf(char **strp, const char *fmt, ...) {
68
69    int res = 0;
70    va_list args;
71
72    va_start(args, fmt);
73    res = asprintf(strp, fmt, args);
74    if (res == -1) {
75        mr_log_exit(-1,"Unable to alloc memory in mr_asprintf\nExiting...");
76    }
77    va_end(args);
78}
79
80/*
81 * Function that properly allocates a string from another one
82 * freeing it before in any case
83 */
84void mr_allocstr(char *alloc, const char *orig) {
85
86    mr_free((void *)alloc); 
87    mr_asprintf(&alloc, orig);
88}
Note: See TracBrowser for help on using the repository browser.