Skip to content

Commit

Permalink
xmalloc: tighten up xzfree() macro
Browse files Browse the repository at this point in the history
The assertion provides some protection against bad calls, both at
compile time (by perhaps triggering a sequence-point warning),
and at run time (by detecting if the ptr argument is unstable when
reused).

This won't protect against all macro-argument-with-side-effects
problems, but maybe the comment will help.
  • Loading branch information
elliefm committed Jan 15, 2024
1 parent 9988b21 commit 4ba9878
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions lib/xmalloc.h
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
/* for free() */
#include <stdlib.h>

#include "assert.h"

extern void *xmalloc (size_t size);
extern void *xzmalloc (size_t size);
extern void *xcalloc (size_t nmemb, size_t size);
Expand All @@ -58,9 +60,14 @@ extern char *xstrdupsafe (const char *str);
extern char *xstrndup (const char *str, size_t len);
extern void *xmemdup (const void *ptr, size_t size);

// free a pointer and also zero it
#define xzfree(ptr) do { \
if (ptr) { free(ptr); ptr = NULL; } \
/* free a pointer and also zero it
*
* CAUTION: ptr argument is evaluated multiple times, beware side effects!
*/
#define xzfree(ptr) do { \
assert((ptr) == (ptr)); \
free(ptr); \
(ptr) = NULL; \
} while (0)

/* Functions using xmalloc.h must provide a function called fatal() conforming
Expand Down

0 comments on commit 4ba9878

Please sign in to comment.