]> granicus.if.org Git - fcron/blob - mem.c
2ce01072474dac788a258f8fcebce181b12d6e5f
[fcron] / mem.c
1 /*
2  * FCRON - periodic command scheduler
3  *
4  *  Copyright 2000-2013 Thibault Godouet <fcron@free.fr>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  *  The GNU General Public License can also be found in the file
21  *  `LICENSE' that comes with the fcron source distribution.
22  */
23
24 #include "global.h"
25 #include "mem.h"
26
27 #if defined(__sun)
28 /* Solaris 10 has no strndup() */
29 char *
30 strndup(const char *s, size_t n)
31     /* Written by Kaveh R. Ghazi <ghazi@caip.rutgers.edu> */
32 {
33     char *result;
34     size_t len = strlen(s);
35
36     if (n < len)
37         len = n;
38
39     result = (char *)malloc(len + 1);
40     if (!result)
41         return 0;
42
43     memcpy(result, s, len);
44     result[len] = '\0';
45     return (result);
46 }
47 #endif
48
49 char *
50 strdup2(const char *str)
51 {
52     char *ptr;
53
54     if (str == NULL)
55         return NULL;
56
57     ptr = strdup(str);
58
59     if (!ptr)
60         die_e("Could not strdup()");
61
62     return (ptr);
63 }
64
65 char *
66 strndup2(const char *str, size_t n)
67 {
68     char *ptr;
69
70     if (str == NULL)
71         return NULL;
72
73     ptr = strndup(str, n);
74
75     if (!ptr)
76         die_e("Could not strdup()");
77
78     return (ptr);
79 }
80
81 void *
82 alloc_safe(size_t len, const char *desc)
83 /* allocate len-bytes of memory, and return the pointer.
84  * Die with a log message if there is any error */
85 {
86     void *ptr = NULL;
87
88     ptr = calloc(1, len);
89     if (ptr == NULL) {
90         die_e("Could not allocate %d bytes of memory%s%s", len,
91               (desc) ? "for " : "", desc);
92     }
93     return ptr;
94 }
95
96 void *
97 realloc_safe(void *cur, size_t len, const char *desc)
98 /* allocate len-bytes of memory, and return the pointer.
99  * Die with a log message if there is any error */
100 {
101     void *new = NULL;
102
103     new = realloc(cur, len);
104     if (new == NULL) {
105         die_e("Could not reallocate %d bytes of memory%s%s", len,
106               (desc) ? "for " : "", desc);
107     }
108     return new;
109 }