Make memory management uniform: _everything_ now goes through the
[u/mdw/putty] / misc.c
CommitLineData
374330e2 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
13static FILE *fp = NULL;
14
15void mlog(char *file, int line) {
c662dbc0 16 if (!fp) {
374330e2 17 fp = fopen("putty_mem.log", "w");
c662dbc0 18 setvbuf(fp, NULL, _IONBF, BUFSIZ);
19 }
374330e2 20 if (fp)
21 fprintf (fp, "%s:%d: ", file, line);
22}
23#endif
24
25void *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
39void *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
57void 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}
c82bda52 70
71#ifdef DEBUG
72static FILE *debug_fp = NULL;
73static int debug_got_console = 0;
74
75void dprintf(char *fmt, ...) {
76 char buf[2048];
77 DWORD dw;
78 va_list ap;
79
80 if (!debug_got_console) {
81 AllocConsole();
82 debug_got_console = 1;
83 }
84 if (!debug_fp) {
85 debug_fp = fopen("debug.log", "w");
86 }
87
88 va_start(ap, fmt);
89 vsprintf(buf, fmt, ap);
90 WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, strlen(buf), &dw, NULL);
91 fputs(buf, debug_fp);
92 fflush(debug_fp);
93 va_end(ap);
94}
95#endif