puttymem.h 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * PuTTY memory-handling header.
  3. */
  4. #ifndef PUTTY_PUTTYMEM_H
  5. #define PUTTY_PUTTYMEM_H
  6. #include <stddef.h> /* for size_t */
  7. #include <string.h> /* for memcpy() */
  8. /* #define MALLOC_LOG do this if you suspect putty of leaking memory */
  9. #ifdef MALLOC_LOG
  10. #define smalloc(z) (mlog(__FILE__,__LINE__), safemalloc(z,1))
  11. #define snmalloc(z,s) (mlog(__FILE__,__LINE__), safemalloc(z,s))
  12. #define srealloc(y,z) (mlog(__FILE__,__LINE__), saferealloc(y,z,1))
  13. #define snrealloc(y,z,s) (mlog(__FILE__,__LINE__), saferealloc(y,z,s))
  14. #define sfree(z) (mlog(__FILE__,__LINE__), safefree(z))
  15. void mlog(char *, int);
  16. #else
  17. #define smalloc(z) safemalloc(z,1)
  18. #define snmalloc safemalloc
  19. #define srealloc(y,z) saferealloc(y,z,1)
  20. #define snrealloc saferealloc
  21. #define sfree safefree
  22. #endif
  23. void *safemalloc(size_t, size_t);
  24. void *saferealloc(void *, size_t, size_t);
  25. void safefree(void *);
  26. /*
  27. * Direct use of smalloc within the code should be avoided where
  28. * possible, in favour of these type-casting macros which ensure
  29. * you don't mistakenly allocate enough space for one sort of
  30. * structure and assign it to a different sort of pointer.
  31. *
  32. * The nasty trick in sresize with sizeof arranges for the compiler,
  33. * in passing, to type-check the expression ((type *)0 == (ptr)), i.e.
  34. * to type-check that the input pointer is a pointer to the correct
  35. * type. The construction sizeof(stuff) ? (b) : (b) looks like a
  36. * violation of the first principle of safe macros, but in fact it's
  37. * OK - although it _expands_ the macro parameter more than once, it
  38. * only _evaluates_ it once, so it's still side-effect safe.
  39. */
  40. #define snew(type) ((type *)snmalloc(1, sizeof(type)))
  41. #define snewn(n, type) ((type *)snmalloc((n), sizeof(type)))
  42. #define sresize(ptr, n, type) \
  43. ((type *)snrealloc(sizeof((type *)0 == (ptr)) ? (ptr) : (ptr), \
  44. (n), sizeof(type)))
  45. /*
  46. * For cases where you want to allocate a struct plus a subsidiary
  47. * data buffer in one step, this macro lets you add a constant to the
  48. * amount malloced.
  49. *
  50. * Since the return value is already cast to the struct type, a
  51. * pointer to that many bytes of extra data can be conveniently
  52. * obtained by simply adding 1 to the returned pointer!
  53. * snew_plus_get_aux is a handy macro that does that and casts the
  54. * result to void *, so you can assign it straight to wherever you
  55. * wanted it.
  56. */
  57. #define snew_plus(type, extra) ((type *)snmalloc(1, sizeof(type) + (extra)))
  58. #define snew_plus_get_aux(ptr) ((void *)((ptr) + 1))
  59. #endif