]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - misc.c
Created a shiny new abstraction for the socket handling. Has many
[PuTTY.git] / 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         setvbuf(fp, NULL, _IONBF, BUFSIZ);
19     }
20     if (fp)
21         fprintf (fp, "%s:%d: ", file, line);
22 }
23 #endif
24
25 void *safemalloc(size_t size) {
26     void *p = malloc (size);
27     if (!p) {
28         MessageBox(NULL, "Out of memory!", "PuTTY Fatal Error",
29                    MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
30         exit(1);
31     }
32 #ifdef MALLOC_LOG
33     if (fp)
34         fprintf(fp, "malloc(%d) returns %p\n", size, p);
35 #endif
36     return p;
37 }
38
39 void *saferealloc(void *ptr, size_t size) {
40     void *p;
41     if (!ptr)
42         p = malloc (size);
43     else
44         p = realloc (ptr, size);
45     if (!p) {
46         MessageBox(NULL, "Out of memory!", "PuTTY Fatal Error",
47                    MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
48         exit(1);
49     }
50 #ifdef MALLOC_LOG
51     if (fp)
52         fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
53 #endif
54     return p;
55 }
56
57 void safefree(void *ptr) {
58     if (ptr) {
59 #ifdef MALLOC_LOG
60         if (fp)
61             fprintf(fp, "free(%p)\n", ptr);
62 #endif
63         free (ptr);
64     }
65 #ifdef MALLOC_LOG
66     else if (fp)
67         fprintf(fp, "freeing null pointer - no action taken\n");
68 #endif
69 }