puttymem.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. #endif