Subversion Repositories Games.Carmageddon

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. /**
  2.         libsmacker - A C library for decoding .smk Smacker Video files
  3.         Copyright (C) 2012-2017 Greg Kennedy
  4.  
  5.         See smacker.h for more information.
  6.  
  7.         smk_malloc.h
  8.                 "Safe" implementations of malloc and free.
  9.                 Verbose implementation of assert.
  10. */
  11.  
  12. #ifndef SMK_MALLOC_H
  13. #define SMK_MALLOC_H
  14.  
  15. /* calloc */
  16. #include <stdlib.h>
  17. /* fprintf */
  18. #include <stdio.h>
  19.  
  20. /* Error messages from calloc */
  21. #include <errno.h>
  22. #include <string.h>
  23.  
  24. /**
  25.         Verbose assert:
  26.                 branches to an error block if pointer is null
  27. */
  28. #define smk_assert(p) \
  29. { \
  30.         if (!p) \
  31.         { \
  32.                 fprintf(stderr, "libsmacker::smk_assert(" #p "): ERROR: NULL POINTER at line %lu, file %s\n", (unsigned long)__LINE__, __FILE__); \
  33.                 goto error; \
  34.         } \
  35. }
  36.  
  37. /**
  38.         Safe free: attempts to prevent double-free by setting pointer to NULL.
  39.                 Optionally warns on attempts to free a NULL pointer.
  40. */
  41. #define smk_free(p) \
  42. { \
  43.         if (p) \
  44.         { \
  45.                 free(p); \
  46.                 p = NULL; \
  47.         } \
  48. /*      else \
  49.         { \
  50.                 fprintf(stderr, "libsmacker::smk_free(" #p ") - Warning: attempt to free NULL pointer (file: %s, line: %lu)\n", __FILE__, (unsigned long)__LINE__); \
  51.         } */ \
  52. }
  53.  
  54. /**
  55.         Safe malloc: exits if calloc() returns NULL.
  56.                 Also initializes blocks to 0.
  57.         Optionally warns on attempts to malloc over an existing pointer.
  58.         Ideally, one should not exit() in a library. However, if you cannot
  59.                 calloc(), you probably have bigger problems.
  60. */
  61. #define smk_malloc(p, x) \
  62. { \
  63. /*      if (p) \
  64.         { \
  65.                 fprintf(stderr, "libsmacker::smk_malloc(" #p ", %lu) - Warning: freeing non-NULL pointer before calloc (file: %s, line: %lu)\n", (unsigned long) (x), __FILE__, (unsigned long)__LINE__); \
  66.                 free(p); \
  67.         } */ \
  68.         p = calloc(1, x); \
  69.         if (!p) \
  70.         { \
  71.                 fprintf(stderr, "libsmacker::smk_malloc(" #p ", %lu) - ERROR: calloc() returned NULL (file: %s, line: %lu)\n\tReason: [%d] %s\n", \
  72.                         (unsigned long) (x), __FILE__, (unsigned long)__LINE__, errno, strerror(errno)); \
  73.                 exit(EXIT_FAILURE); \
  74.         } \
  75. }
  76.  
  77. #endif
  78.