Fwd: strdup(NULL) supposed to create SIGSEGV?

Bakul Shah bakul at bitblocks.com
Wed Apr 23 19:22:36 UTC 2008

On Wed, 23 Apr 2008 11:03:10 BST Robert Watson <rwatson at FreeBSD.org>  wrote:
> On Wed, 23 Apr 2008, Garrett Cooper wrote:
> > Of course I did some more research after you guys gave me some replies and 
> > realized I'm not the first person to bumble across this fact, but I haven't
> > found FreeBSD or Linux documentation supporting that errata. It was harmless
> > in my tiny program, but I would hate to be someone adding that assumption to
> > a larger project with multiple threads and a fair number of lines...
> Consider the following counter-arguments:
> - In C, a string is a sequence of non-nul characters followed by a nul
>    character terminating the string.  NULL is therefore not a valid string.
> - Currently, strdup(3) has an unambiguous error model: if it returns a
>    non-NULL string has succeeded, and if it has failed, it returns NULL and
>    sets errno.  If NULL becomes a successful return from strdup(3), then this
>    is no longer the case, breaking the assumptions of currently correct
>    consumers.

I suspect Garrett has a more fundamental misunderstanding.

C is a low level language and for efficiency sake most of its
standard functions *do not check* that their inputs are legal
-- it is the caller's responsibility to give valid inputs and
when that is not done, all bets are off!  In general a NULL
is an illegal value to pass in place of any kind of pointer.

The *exception* is where a function is explicitly prepared to
handle NULLs.  One must read its man page carefully and if it
doesn't say anything about how NULLs in place of ptrs are
handled, one must not pass in NULLs!

He should also note that function specifications (e.g. man
pages) will specify what are legal inputs but usually they
will *not* specify what happens when illegal inputs are given
since a) that set is usually much much larger, and b) the
effect is likely to be machine dependent.


More information about the freebsd-hackers mailing list