This is the mail archive of the
glibc-linux@ricardo.ecn.wfu.edu
mailing list for the glibc project.
Re: bug in strlen
- To: glibc-linux at ricardo dot ecn dot wfu dot edu
- Subject: Re: bug in strlen
- From: Kaz Kylheku <kaz at ashi dot footprints dot net>
- Date: Thu, 7 Sep 2000 10:11:47 -0700 (PDT)
- Reply-To: glibc-linux at ricardo dot ecn dot wfu dot edu
On Thu, 7 Sep 2000 rashutos@in.ibm.com wrote:
> Date: Thu, 7 Sep 2000 15:18:39 +0530
> From: rashutos@in.ibm.com
> Reply-To: glibc-linux@ricardo.ecn.wfu.edu
> To: glibc-linux@ricardo.ecn.wfu.edu
> Subject: bug in strlen
>
> Hello,
>
> the strlen() function has a bug ... If you pass a NULL string to strlen(),
> the program crashes ... for NULL pointer dereference (SIGSEGV)
Don't be ridiculous! The behavior is *undefined* if you pass strlen a bad
pointer; read the C standard. The n843 draft of the C99 standard says:
7.1.4 Use of library functions
Each of the following statements applies unless explicitly
stated otherwise in the detailed descriptions that follow:
If an argument to a function has an invalid value (such as a
value outside the domain of the function, or a pointer outside
the address space of the program, or a null pointer) or a type
(after promotion) not expected by a function with variable
number of arguments, the behavior is undefined.
The ``explicitly stated otherwise'' covers such cases like free: the
deallocation function free function may have a null argument, which causes it
to have no effect.
What is the length of a non-existent string, anyway? It's not zero; a zero
length string requires at least one byte of storage to store the terminating
null.
Why should correct programs---ones which do not pass null pointers to the
strlen() function---have to pay for a check for something that doesn't happen?
There are some legacy programs which depend on the null pointer being able to access a valid piece of memory. You find in them constructs like:
*strchr(str, '\n') = 0; /* nuke the newline, if it exists */
These programs are broken; it is these programs that must be fixed, rather than
every library or compiler they are ported to.