The meaning of malloc returning NULL

NULL or (void *)0 as a return value for malloc means it has failed right?  Looking at the man page for malloc in Windows cygwin says that it means its failed.  But sometimes, malloc can reasonably return NULL even when it hasnt failed. 

 More portable and correct is setting errno.  Address 0, is a valid memory address.  I’ve never seen the heap put at 0, but no-one defines it as invalid.. except some unix implementations.

A quick google shows that not all systems implement this behaviour though.  Make sure to check the specifications for your particular system.
Better perhaps than malloc as an example, is mmap.  Sometimes I’ve wanted to return a mapping at address 0 for particular reasons.  Checking for errno is the only way gauranteed to give you the status. 

 As a developer I saw alot of bugs introduced by coders who assumed the return value and not errno was the definative source of success status.  You should always check the return value first, and if that indicates a possible failure, then check errno.

But then again, not all systems implement this (apparently).  How messy is ‘portable’ code to become if malloc has to be wrapped to check for errno, even if its correct?  For the record, I dont check errno on malloc ;-)  But on some systems, it is defined as being incorrect.  Not that this would ever be true in real life.

 I am, through all this, trying to make the point that when we treat a pointer as an address, then 0 is a valid response.  This is something we should keep in mind when working with pointers.

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