misc.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <windows.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include "putty.h"
  5. /* My own versions of malloc, realloc and free. Because I want malloc and
  6. * realloc to bomb out and exit the program if they run out of memory,
  7. * realloc to reliably call malloc if passed a NULL pointer, and free
  8. * to reliably do nothing if passed a NULL pointer. Of course we can also
  9. * put trace printouts in, if we need to. */
  10. #ifdef MALLOC_LOG
  11. static FILE *fp = NULL;
  12. void mlog(char *file, int line) {
  13. if (!fp) {
  14. fp = fopen("putty_mem.log", "w");
  15. setvbuf(fp, NULL, _IONBF, BUFSIZ);
  16. }
  17. if (fp)
  18. fprintf (fp, "%s:%d: ", file, line);
  19. }
  20. #endif
  21. void *safemalloc(size_t size) {
  22. void *p = malloc (size);
  23. if (!p) {
  24. MessageBox(NULL, "Out of memory!", "PuTTY Fatal Error",
  25. MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
  26. exit(1);
  27. }
  28. #ifdef MALLOC_LOG
  29. if (fp)
  30. fprintf(fp, "malloc(%d) returns %p\n", size, p);
  31. #endif
  32. return p;
  33. }
  34. void *saferealloc(void *ptr, size_t size) {
  35. void *p;
  36. if (!ptr)
  37. p = malloc (size);
  38. else
  39. p = realloc (ptr, size);
  40. if (!p) {
  41. MessageBox(NULL, "Out of memory!", "PuTTY Fatal Error",
  42. MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
  43. exit(1);
  44. }
  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. void safefree(void *ptr) {
  52. if (ptr) {
  53. #ifdef MALLOC_LOG
  54. if (fp)
  55. fprintf(fp, "free(%p)\n", ptr);
  56. #endif
  57. free (ptr);
  58. }
  59. #ifdef MALLOC_LOG
  60. else if (fp)
  61. fprintf(fp, "freeing null pointer - no action taken\n");
  62. #endif
  63. }