GuardedAlloc: safer MEM_SAFE_FREE
authorCampbell Barton <ideasman42@gmail.com>
Sat, 28 Feb 2015 03:41:15 +0000 (14:41 +1100)
committerCampbell Barton <ideasman42@gmail.com>
Thu, 12 Mar 2015 12:49:15 +0000 (23:49 +1100)
only instantiate the argument once,
so MEM_SAFE_FREE(array[i++]), won't cause incorrect behavior.

intern/guardedalloc/MEM_guardedalloc.h

index f0a69f993854ff56bbcf775ef1951194d438f510..05a98c1a4e5c0266952156e889c86821d1e3224c 100644 (file)
@@ -177,7 +177,23 @@ extern "C" {
        /** Get the peak memory usage in bytes, including mmap allocations. */
        extern size_t (*MEM_get_peak_memory)(void) ATTR_WARN_UNUSED_RESULT;
 
-#define MEM_SAFE_FREE(v) if (v) { MEM_freeN(v); v = NULL; } (void)0
+#ifdef __GNUC__
+#define MEM_SAFE_FREE(v) do { \
+       typeof(&(v)) _v = &(v); \
+       if (*_v) { \
+               MEM_freeN(*_v); \
+               *_v = NULL; \
+       } \
+} while (0)
+#else
+#define MEM_SAFE_FREE(v) do { \
+       void ** _v = (void **)&(v); \
+       if (*_v) { \
+               MEM_freeN(*_v); \
+               *_v = NULL; \
+       } \
+} while (0)
+#endif
 
 /* overhead for lockfree allocator (use to avoid slop-space) */
 #define MEM_SIZE_OVERHEAD sizeof(size_t)