Initial checkin: beta 0.43
[u/mdw/putty] / misc.c
1 #include <windows.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include "putty.h"
5
6 /* My own versions of malloc, realloc and free. Because I want malloc and
7 * realloc to bomb out and exit the program if they run out of memory,
8 * realloc to reliably call malloc if passed a NULL pointer, and free
9 * to reliably do nothing if passed a NULL pointer. Of course we can also
10 * put trace printouts in, if we need to. */
11
12 #ifdef MALLOC_LOG
13 static FILE *fp = NULL;
14
15 void mlog(char *file, int line) {
16 if (!fp)
17 fp = fopen("putty_mem.log", "w");
18 if (fp)
19 fprintf (fp, "%s:%d: ", file, line);
20 }
21 #endif
22
23 void *safemalloc(size_t size) {
24 void *p = malloc (size);
25 if (!p) {
26 MessageBox(NULL, "Out of memory!", "PuTTY Fatal Error",
27 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
28 exit(1);
29 }
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 MessageBox(NULL, "Out of memory!", "PuTTY Fatal Error",
45 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
46 exit(1);
47 }
48 #ifdef MALLOC_LOG
49 if (fp)
50 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
51 #endif
52 return p;
53 }
54
55 void safefree(void *ptr) {
56 if (ptr) {
57 #ifdef MALLOC_LOG
58 if (fp)
59 fprintf(fp, "free(%p)\n", ptr);
60 #endif
61 free (ptr);
62 }
63 #ifdef MALLOC_LOG
64 else if (fp)
65 fprintf(fp, "freeing null pointer - no action taken\n");
66 #endif
67 }