-
Notifications
You must be signed in to change notification settings - Fork 20
/
xmalloc.c
65 lines (55 loc) · 1.16 KB
/
xmalloc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* A safer saner malloc, for careless programmers
* $Revision: 7.16 $
*/
#include <stdlib.h>
#include <limits.h>
#include "compat.h"
#include "sc.h"
static void fatal(char *);
#define MAGIC (double)1234567890.12344
void *
scxmalloc(size_t n)
{
void *ptr;
if ((ptr = malloc(n + sizeof(double))) == NULL)
fatal("scxmalloc: no memory");
*((double *) ptr) = MAGIC; /* magic number */
return(ptr + sizeof(double));
}
/* we make sure realloc will do a malloc if needed */
void *
scxrealloc(void *ptr, size_t n)
{
if (ptr == NULL)
return(scxmalloc(n));
ptr -= sizeof(double);
if (*((double *) ptr) != MAGIC)
fatal("scxrealloc: storage not scxmalloc'ed");
if ((ptr = realloc(ptr, n + sizeof(double))) == NULL)
fatal("scxmalloc: no memory");
*((double *) ptr) = MAGIC; /* magic number */
return(ptr + sizeof(double));
}
void
scxfree(void *p)
{
if (p == NULL)
fatal("scxfree: NULL");
p -= sizeof(double);
if (*((double *) p) != MAGIC)
fatal("scxfree: storage not malloc'ed");
free(p);
}
static void
fatal(char *str)
{
#ifndef PSC
deraw(1);
#endif /* PSC */
fprintf(stderr, "%s\n", str);
#ifndef PSC
diesave();
#endif /* PSC */
exit(1);
}