Initial commit of a basically working but severely unpolished
[sgt/agedu] / malloc.h
CommitLineData
70322ae3 1/*
2 * malloc.h: safe wrappers around malloc, realloc, free, strdup
3 */
4
5#ifndef AGEDU_MALLOC_H
6#define AGEDU_MALLOC_H
7
8#include <stddef.h>
9
10/*
11 * smalloc should guarantee to return a useful pointer.
12 */
13void *smalloc(size_t size);
14
15/*
16 * srealloc should guaranteeably be able to realloc NULL
17 */
18void *srealloc(void *p, size_t size);
19
20/*
21 * sfree should guaranteeably deal gracefully with freeing NULL
22 */
23void sfree(void *p);
24
25/*
26 * dupstr is like strdup, but with the never-return-NULL property
27 * of smalloc (and also reliably defined in all environments :-)
28 */
29char *dupstr(const char *s);
30
31/*
32 * dupfmt is a bit like printf, but does its own allocation and
33 * returns a dynamic string. It also supports a different (and
34 * much less featureful) set of format directives:
35 *
36 * - %D takes no argument, and gives the current date and time in
37 * a format suitable for an HTTP Date header
38 * - %d takes an int argument and formats it like normal %d (but
39 * doesn't support any of the configurability of standard
40 * printf)
41 * - %s takes a const char * and formats it like normal %s
42 * (again, no fine-tuning available)
43 * - %S takes an int followed by a const char *. If the int is
44 * zero, it behaves just like %s. If the int is nonzero, it
45 * transforms the string by stuffing a \r before every \n.
46 */
47char *dupfmt(const char *fmt, ...);
48
49/*
50 * snew allocates one instance of a given type, and casts the
51 * result so as to type-check that you're assigning it to the
52 * right kind of pointer. Protects against allocation bugs
53 * involving allocating the wrong size of thing.
54 */
55#define snew(type) \
56 ( (type *) smalloc (sizeof (type)) )
57
58/*
59 * snewn allocates n instances of a given type, for arrays.
60 */
61#define snewn(number, type) \
62 ( (type *) smalloc ((number) * sizeof (type)) )
63
64/*
65 * sresize wraps realloc so that you specify the new number of
66 * elements and the type of the element, with the same type-
67 * checking advantages. Also type-checks the input pointer.
68 */
69#define sresize(array, number, type) \
70 ( (void)sizeof((array)-(type *)0), \
71 (type *) srealloc ((array), (number) * sizeof (type)) )
72
73#endif /* AGEDU_MALLOC_H */