chiark / gitweb /
Initial revision
[ssr] / StraySrc / Utilities / c / alloc
1 /*
2  * alloc.c
3  *
4  * Trivial veneers for allocating memory
5  *
6  * © 1998 Straylight/Edgeware
7  */
8
9 /*----- Licensing note ----------------------------------------------------*
10  *
11  * This file is part of Straylight's core utilities (coreutils).
12  *
13  * Coreutils is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2, or (at your option)
16  * any later version.
17  *
18  * Coreutils is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with coreutils.  If not, write to the Free Software Foundation,
25  * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26  */
27
28 /*----- Header files ------------------------------------------------------*/
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include "alloc.h"
35
36 /*----- Main code ---------------------------------------------------------*/
37
38 /* --- @xmalloc@ --- *
39  *
40  * Arguments:   @size_t sz@ = size of block to allocate
41  *
42  * Returns:     Pointer to newly allocated block.
43  *
44  * Use:         Returns a block of the requested size, or not at all.
45  */
46
47 void *xmalloc(size_t sz)
48 {
49   void *p = malloc(sz);
50   if (!p) {
51     fprintf(stderr, "inst: not enough memory\n");
52     exit(1);
53   }
54   return (p);
55 }
56
57 /* --- @xrealloc@ --- *
58  *
59  * Arguments:   @void *p@ = pointer to a block of memory
60  *              @size_t sz@ = size we want it to be
61  *
62  * Returns:     Pointer to resized block
63  *
64  * Use:         Resizes a block.  Returns the resized block, or not at all.
65  */
66
67 void *xrealloc(void *p, size_t sz)
68 {
69   p = realloc(p, sz);
70   if (!p) {
71     fprintf(stderr, "inst: not enough memory\n");
72     exit(1);
73   }
74   return (p);
75 }
76
77 /* --- @xstrdup@ --- *
78  *
79  * Arguments:   @const char *p@ = pointer to string to copy
80  *
81  * Returns:     Pointer to a copy of the string.
82  *
83  * Use:         Returns a copy of a string, or not at all.
84  */
85
86 char *xstrdup(const char *p)
87 {
88   size_t sz = strlen(p) + 1;
89   char *q = xmalloc(sz);
90   memcpy(q, p, sz);
91   return (q);
92 }
93
94 /*----- That's all, folks -------------------------------------------------*/