BULK: Change syntax to drop "7:command ".
[pwmd.git] / src / mem.c
blob30a1d3abee52ebe7a4a12c107d8e401a1afa1795
1 /*
2 Copyright (C) 2006-2018 Ben Kibbey <bjk@luxsci.net>
4 This file is part of pwmd.
6 Pwmd 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.
11 Pwmd 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.
16 You should have received a copy of the GNU General Public License
17 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <string.h>
27 #include <stddef.h>
29 #include "mem.h"
31 void *
32 xrealloc_gpgrt (void *p, size_t n)
34 if (n)
36 if (p)
37 return xrealloc (p, n);
39 return xmalloc (n);
42 xfree (p);
43 return NULL;
46 #ifndef MEM_DEBUG
47 struct memchunk_s
49 size_t size;
50 char data[1];
51 } __attribute ((packed));
53 void
54 xfree (void *ptr)
56 struct memchunk_s *m;
57 void *p;
59 if (!ptr)
60 return;
62 m = (struct memchunk_s *)((char *)ptr-(offsetof (struct memchunk_s, data)));
63 p = (void *)((char *)m+(offsetof (struct memchunk_s, data)));
64 wipememory (p, 0, m->size);
65 free (m);
68 void *
69 xmalloc (size_t size)
71 struct memchunk_s *m;
73 if (!size)
74 return NULL;
76 m = malloc (sizeof (struct memchunk_s)+size);
77 if (!m)
78 return NULL;
80 m->size = size;
81 return (void *)((char *)m+(offsetof (struct memchunk_s, data)));
84 void *
85 xcalloc (size_t nmemb, size_t size)
87 void *p;
88 struct memchunk_s *m;
90 m = malloc (sizeof (struct memchunk_s)+(nmemb*size));
91 if (!m)
92 return NULL;
94 m->size = nmemb*size;
95 p = (void *)((char *)m+(offsetof (struct memchunk_s, data)));
96 memset (p, 0, m->size);
97 return p;
100 void *
101 xrealloc (void *ptr, size_t size)
103 void *p, *np;
104 struct memchunk_s *m, *mp;
105 size_t n;
107 if (!size && ptr)
109 m = (struct memchunk_s *)((char *)ptr-(offsetof (struct memchunk_s, data)));
110 p = (void *)((char *)m+(offsetof (struct memchunk_s, data)));
111 wipememory (p, 0, m->size);
112 free (m);
113 return NULL;
115 else if (!ptr)
116 return xmalloc (size);
118 m = malloc (sizeof (struct memchunk_s)+size);
119 if (!m)
120 return NULL;
122 m->size = size;
123 np = (void *)((char *)m+(offsetof (struct memchunk_s, data)));
125 mp = (struct memchunk_s *)((char *)ptr-(offsetof (struct memchunk_s, data)));
126 p = (void *)((char *)mp+(offsetof (struct memchunk_s, data)));
128 n = size > mp->size ? mp->size : size;
129 memcpy (np, p, n);
130 wipememory (p, 0, mp->size);
132 free (mp);
133 return (void *)((char *)m+(offsetof (struct memchunk_s, data)));
136 #endif