Fwd: strdup(NULL) supposed to create SIGSEGV?

Robert Watson rwatson at FreeBSD.org
Wed Apr 23 10:03:11 UTC 2008


On Wed, 23 Apr 2008, Garrett Cooper wrote:

>> But strdup uses malloc, which is a system call (from the strdup manual: If 
>> insufficient memory is available, NULL is returned and errno is set to 
>> ENOMEM.)

FYI, malloc(3) is actually a library call, and while it obviously does invoke 
system calls (mmap(2) on modern systems), it has some fairly complex logic for 
managing and caching memory provided by the kernel.

> I was more concerned about the fact that there wasn't any documentation that 
> said something -- either implicitly or explicitly -- that strdup(NULL) 
> causes a segfault.
>
> 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.

Robert N M Watson
Computer Laboratory
University of Cambridge


More information about the freebsd-hackers mailing list