Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 23 Apr 2008 11:03:10 +0100 (BST)
From:      Robert Watson <rwatson@FreeBSD.org>
To:        Garrett Cooper <yanefbsd@gmail.com>
Cc:        hackers@freebsd.org
Subject:   Re: Fwd: strdup(NULL) supposed to create SIGSEGV?
Message-ID:  <20080423105319.V35222@fledge.watson.org>
In-Reply-To: <7d6fde3d0804230219q13d204f2wda4a5f271b9a0e66@mail.gmail.com>
References:  <7d6fde3d0804222240j6b42b77yd86d8accb5a959fa@mail.gmail.com> <20080423025048.6b51a580@bhuda.mired.org> <5F412E73-29FC-4876-A6F0-9BC269876192@bitpowder.com> <7d6fde3d0804230219x209bd707u30150581abc74802@mail.gmail.com> <7d6fde3d0804230219q13d204f2wda4a5f271b9a0e66@mail.gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help
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



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20080423105319.V35222>