malloc.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * malloc.c: safe wrappers around malloc, realloc, free, strdup
  3. */
  4. #ifndef NO_STDINT_H
  5. #include <stdint.h>
  6. #endif
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include "puzzles.h"
  10. /*
  11. * smalloc should guarantee to return a useful pointer - we
  12. * can do nothing except die when it's out of memory anyway.
  13. */
  14. void *smalloc(size_t size) {
  15. void *p;
  16. #ifdef PTRDIFF_MAX
  17. if (size > PTRDIFF_MAX)
  18. fatal("allocation too large");
  19. #endif
  20. p = malloc(size);
  21. if (!p)
  22. fatal("out of memory");
  23. return p;
  24. }
  25. /*
  26. * sfree should guaranteeably deal gracefully with freeing NULL
  27. */
  28. void sfree(void *p) {
  29. if (p) {
  30. free(p);
  31. }
  32. }
  33. /*
  34. * srealloc should guaranteeably be able to realloc NULL
  35. */
  36. void *srealloc(void *p, size_t size) {
  37. void *q;
  38. #ifdef PTRDIFF_MAX
  39. if (size > PTRDIFF_MAX)
  40. fatal("allocation too large");
  41. #endif
  42. if (p) {
  43. q = realloc(p, size);
  44. } else {
  45. q = malloc(size);
  46. }
  47. if (!q)
  48. fatal("out of memory");
  49. return q;
  50. }
  51. /*
  52. * dupstr is like strdup, but with the never-return-NULL property
  53. * of smalloc (and also reliably defined in all environments :-)
  54. */
  55. char *dupstr(const char *s) {
  56. char *r = smalloc(1+strlen(s));
  57. strcpy(r,s);
  58. return r;
  59. }