Fixes.
[yaz-moved-to-github.git] / util / dmalloc.c
1 /*
2  * Copyright (C) 1994, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: dmalloc.c,v $
7  * Revision 1.2  1995-04-10 10:23:50  quinn
8  * Fixes.
9  *
10  * Revision 1.1  1995/03/27  08:35:17  quinn
11  * Created util library
12  * Added memory debugging module. Imported options-manager
13  *
14  *
15  */
16
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <string.h>
20
21 static const unsigned long head = 0xaabbccdd;
22 static const unsigned long tail = 0x11223344;
23 static const unsigned long freed = 0xffeeffee;
24
25 void *d_malloc(char *file, int line, int nbytes)
26 {
27     char *res;
28     int long len;
29
30     if (!(res = malloc(nbytes + 3 * sizeof(long))))
31         return 0;
32     fprintf(stderr, "---d_malloc, '%s':%d, %d->%p\n",
33         file, line, nbytes, res + 2 * sizeof(long));
34     len = nbytes;
35     memcpy(res, &head, sizeof(long));
36     memcpy(res + sizeof(long), &len, sizeof(long));
37     res += 2 * sizeof(long);
38     memcpy(res + nbytes, &tail, sizeof(long));
39     return res;
40 }
41
42 void d_free(char *file, int line, char *ptr)
43 {
44     long len;
45
46     if (memcmp(&head, ptr - 2 * sizeof(long), sizeof(long)))
47         abort();
48     memcpy(ptr, &freed, sizeof(long));
49     memcpy(&len, ptr - sizeof(long), sizeof(long));
50     if (memcmp(ptr + len, &tail, sizeof(long)))
51         abort();
52     fprintf(stderr, "---d_free, '%s':%d, %p (%d)\n",
53         file, line, ptr, len);
54     free(ptr - 2 * sizeof(long));
55     return;
56 }
57
58 void *d_realloc(char *file, int line, char *ptr, int nbytes)
59 {
60     long len, nlen = nbytes;
61     char *p = ptr;
62     char *r;
63
64     if (memcmp(&head, ptr - 2 * sizeof(long), sizeof(long)))
65         abort();
66     memcpy(&len, ptr - sizeof(long), sizeof(long));
67     if (memcmp(ptr + len, &tail, sizeof(long)))
68         abort();
69     if (!(r = realloc(ptr, nbytes + 3 * sizeof(long))))
70         return 0;
71     fprintf(stderr, "---d_realloc, '%s':%d, %d->%d, %p->%p\n",
72         file, line, len, nbytes, p, r + 2 * sizeof(long));
73     memcpy(r, &head, sizeof(long));
74     memcpy(r + sizeof(long), &nlen, sizeof(long));
75     if (r != ptr - 2 * sizeof(long))
76     {
77         memcpy(r + 2 * sizeof(long), ptr, len);
78         memcpy(ptr - 2 * sizeof(long), &freed, sizeof(long));
79     }
80     r += 2 * sizeof(long);
81     memcpy(r + nbytes, &tail, sizeof(long));
82     return r;
83 }