]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - misc.c
Removing one bug, and hunting another
[PuTTY.git] / misc.c
1 /* $Id: misc.c,v 1.2.2.1 1999/02/19 15:24:15 ben Exp $ */
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include "putty.h"
6
7 /* My own versions of malloc, realloc and free. Because I want malloc and
8  * realloc to bomb out and exit the program if they run out of memory,
9  * realloc to reliably call malloc if passed a NULL pointer, and free
10  * to reliably do nothing if passed a NULL pointer. Of course we can also
11  * put trace printouts in, if we need to. */
12
13 #ifdef MALLOC_LOG
14 static FILE *fp = NULL;
15
16 void mlog(char *file, int line) {
17     if (!fp) {
18         fp = fopen("putty_mem.log", "w");
19         setvbuf(fp, NULL, _IONBF, BUFSIZ);
20     }
21     if (fp)
22         fprintf (fp, "%s:%d: ", file, line);
23 }
24 #endif
25
26 void *safemalloc(size_t size) {
27     void *p = malloc (size);
28     if (!p)
29         fatalbox("%s", "Out of memory!");
30 #ifdef MALLOC_LOG
31     if (fp)
32         fprintf(fp, "malloc(%d) returns %p\n", size, p);
33 #endif
34     return p;
35 }
36
37 void *saferealloc(void *ptr, size_t size) {
38     void *p;
39     if (!ptr)
40         p = malloc (size);
41     else
42         p = realloc (ptr, size);
43     if (!p)
44         fatalbox("%s", "Out of memory!");
45 #ifdef MALLOC_LOG
46     if (fp)
47         fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
48 #endif
49     return p;
50 }
51
52 void safefree(void *ptr) {
53     if (ptr) {
54 #ifdef MALLOC_LOG
55         if (fp)
56             fprintf(fp, "free(%p)\n", ptr);
57 #endif
58         free (ptr);
59     }
60 #ifdef MALLOC_LOG
61     else if (fp)
62         fprintf(fp, "freeing null pointer - no action taken\n");
63 #endif
64 }