free(ptr),ptr=NULL;

I’ve seen this type of code before in production environments to help prevent exploitation of double free’s.  It’s often used in OpenBSD software such as OpenSSH (silvio: verify this.. its been 6 years since I looked at the code).

 free(NULL) is valid under many implementations (check to see if its standardized though), and results in immediately returning without action.

A double free is only possible when you have a dangling pointer.  A pointer that points to memory, which is no longer valid.  Assigning the pointer a NULL value makes it no longer dangle.

 Another suggestion is to implement a free wrapper that checks for a double free occuring.  If the pointer is NULL, or perhaps a specially assigned value indicating the pointer has been free’d, then flag an error.


#define free(ptr) free_checker(__FILE__,__LINE__,ptr)
#define FREED_PTR 0x66666666
#define free_checker(file,line,ptr) do { \
  if (ptr == FREED_PTR) \
  fatal_error("DOUBLE FREE in %s line %u\n", file, line); \
  else \
  free(ptr), ptr=FREED_PTR; \
} while(0)

One response to “free(ptr),ptr=NULL;

  1. Long time no see, silvio !

    I take advantage of this blog article to sneak in a comment or two: free(NULL) is only valid in the C standard since C99.

    As for the whole business of trying to prevent double free bugs, I think this is a very good practice indeed, but I add that some malloc() implementations (such as the one in FreeBSD) already checks those kind of mistakes and would warn about it.


    mux

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s