473,395 Members | 1,581 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

NULL to strlen function

Hi Everyone,

I tried the following program unit in Microsoft Visual c++ 6.0 and the
program caused unexpected behavior,

#include <stdio.h>
#include <string.h>

int main()
{
char *p;
p = NULL;
printf("%d\n",strlen(p));
}

Is it that strlen function can't handle NULL pointers?

Jan 11 '07 #1
44 24939

sam_...@yahoo.co.in wrote:
Is it that strlen function can't handle NULL pointers?
Strlen expects a string as an argument. Is a NULL pointer a string?
(Hint: this is a rhetorical question).

Jan 11 '07 #2
sa*****@yahoo.co.in said:
Hi Everyone,

I tried the following program unit in Microsoft Visual c++ 6.0 and the
program caused unexpected behavior,
Undefined behaviour.
#include <stdio.h>
#include <string.h>

int main()
{
char *p;
p = NULL;
printf("%d\n",strlen(p));
}

Is it that strlen function can't handle NULL pointers?
Or is it that strlen returns size_t and your format specifier requires int?

It is impossible to tell which of these two produces the undefined behaviour
you have noticed.

Any good C book will explain the semantics of strlen.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jan 11 '07 #3

<sa*****@yahoo.co.inwrote in message
news:11*********************@o58g2000hsb.googlegro ups.com...
Hi Everyone,

I tried the following program unit in Microsoft Visual c++ 6.0 and the
program caused unexpected behavior,

#include <stdio.h>
#include <string.h>

int main()
{
char *p;
p = NULL;
printf("%d\n",strlen(p));
}

Is it that strlen function can't handle NULL pointers?
My interpretation would be by definition strlen cannot
properly handle a NULL pointer.

Returns

The strlen function returns the number of characters that precede the
terminating null
character.
Jan 11 '07 #4
In article <11*********************@o58g2000hsb.googlegroups. com>,
sa*****@yahoo.co.in wrote:
I tried the following program unit in Microsoft Visual c++ 6.0
and the program caused unexpected behavior,
#include <stdio.h>
#include <string.h>

int main()
{
char *p;
p = NULL;
printf("%d\n",strlen(p));
}
Is it that strlen function can't handle NULL pointers?
There is no requirement that it does.
NULL is not a valid argument for a char* or const char*
in most functions of <string.h>.
This is hinted in by the lack of explict allowance for
NULL in 7.21.1 (String functions conventions) of
ISO/IEC 9899:1999

For an empty string, try
p = "";
Francois Grieu
Jan 11 '07 #5

"Francois Grieu" <fg****@gmail.comwrote in message
news:fg**************************@news-3.proxad.net...
In article <11*********************@o58g2000hsb.googlegroups. com>,
sa*****@yahoo.co.in wrote:
I tried the following program unit in Microsoft Visual c++ 6.0
and the program caused unexpected behavior,

#include <stdio.h>
#include <string.h>

int main()
{
char *p;
p = NULL;
printf("%d\n",strlen(p));
}
Is it that strlen function can't handle NULL pointers?

There is no requirement that it does.
NULL is not a valid argument for a char* or const char*
in most functions of <string.h>.
This is hinted in by the lack of explict allowance for
NULL in 7.21.1 (String functions conventions) of
ISO/IEC 9899:1999

For an empty string, try
p = "";
Francois Grieu
This doesn't need to be hinted by anything.
strlen() returns a size_t i.e. an unsigned integer.
Jan 11 '07 #6
Barry wrote:
"Francois Grieu" <fg****@gmail.comwrote in message
news:fg**************************@news-3.proxad.net...
>In article <11*********************@o58g2000hsb.googlegroups. com>,
sa*****@yahoo.co.in wrote:
I tried the following program unit in Microsoft Visual c++ 6.0
and the program caused unexpected behavior,

#include <stdio.h>
#include <string.h>

int main()
{
char *p;
p = NULL;
printf("%d\n",strlen(p));
}
Is it that strlen function can't handle NULL pointers?

There is no requirement that it does.
NULL is not a valid argument for a char* or const char*
in most functions of <string.h>.
This is hinted in by the lack of explict allowance for
NULL in 7.21.1 (String functions conventions) of
ISO/IEC 9899:1999

For an empty string, try
p = "";

Francois Grieu

This doesn't need to be hinted by anything.
strlen() returns a size_t i.e. an unsigned integer.
Even if that is fixed, it doesn't matter. `strlen` is a
Standard library function, and hence, unless otherwise
specified, is undefined when a pointer argument is null.

As someone else said: NULL isn't a string. So asking for
its string-length is like asking custard for its display
resolution.

--
Chris "first on the Underground!" Dollin
A rock is not a fact. A rock is a rock.

Jan 11 '07 #7
Barry wrote:
I thought (perhaps mistakenly) the question was trying to be more
thoughtful and the OP meant to ask something like:

Why doesn't strlen check for a NULL pointer and return.
If I pass NULL to strlen, then it was a mistake; simply returning would
only server to mask that error, and potentially hide it until my product
was already released. If strlen attempts to dereference NULL then it
will interrupt the program (on every implementation that I use, and yes,
I test this assumption before relying on it on every platform for which
I code).

I prefer my errors to be caught *before* release as much as possible.

--
Clark S. Cox III
cl*******@gmail.com
Jan 11 '07 #8

"Chris Dollin" <ch**********@hp.comwrote in message
news:eo**********@murdoch.hpl.hp.com...
Barry wrote:
"Francois Grieu" <fg****@gmail.comwrote in message
news:fg**************************@news-3.proxad.net...
In article <11*********************@o58g2000hsb.googlegroups. com>,
sa*****@yahoo.co.in wrote:

I tried the following program unit in Microsoft Visual c++ 6.0
and the program caused unexpected behavior,

#include <stdio.h>
#include <string.h>

int main()
{
char *p;
p = NULL;
printf("%d\n",strlen(p));
}

Is it that strlen function can't handle NULL pointers?

There is no requirement that it does.
NULL is not a valid argument for a char* or const char*
in most functions of <string.h>.
This is hinted in by the lack of explict allowance for
NULL in 7.21.1 (String functions conventions) of
ISO/IEC 9899:1999

For an empty string, try
p = "";

Francois Grieu
This doesn't need to be hinted by anything.
strlen() returns a size_t i.e. an unsigned integer.

Even if that is fixed, it doesn't matter. `strlen` is a
Standard library function, and hence, unless otherwise
specified, is undefined when a pointer argument is null.

As someone else said: NULL isn't a string. So asking for
its string-length is like asking custard for its display
resolution.
The OP often posts questions that demonstrate he/she
hasn't applied what he/she should have taken away from
previous responses.

I thought (perhaps mistakenly) the question was trying to
be more thoughtful and the OP meant to ask something like:

Why doesn't strlen check for a NULL pointer and return.
Jan 11 '07 #9
<sa*****@yahoo.co.inwrote in message
news:11*********************@o58g2000hsb.googlegro ups.com...
Hi Everyone,

I tried the following program unit in Microsoft Visual c++ 6.0 and the
program caused unexpected behavior,

#include <stdio.h>
#include <string.h>

int main()
{
char *p;
p = NULL;
printf("%d\n",strlen(p));
}

Is it that strlen function can't handle NULL pointers?
You're apparently a new programmer, so let me add this:

A NULL pointer and a string of length zero are not the same thing.

A NULL pointer traditionally has the value of 0, which is usually an
unsuitable pointer; but in any case it is a reserved value defined to be a
non-functional pointer.

A string of length 0 has a non-NULL pointer, but the area of memory that is
pointed to has its first byte as 0.

The two are very different.
Jan 11 '07 #10
Clark S. Cox III <cl*******@gmail.comwrote:
If I pass NULL to strlen, then it was a mistake
On the contrary, I think it's certainly possible to imagine code that
could profitably take advantage of the hypothetical ability of
strlen() to deal reasonably with a null pointer. Given how the
language is defined, of course, it's a mistake.
only server to mask that error, and potentially hide it until my product
was already released. If strlen attempts to dereference NULL then it
will interrupt the program (on every implementation that I use, and yes,
I test this assumption before relying on it on every platform for which
I code).
If you find a platform for which your assumption does not hold, what
are your plans for testing your code?

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
Jan 11 '07 #11
"Christopher Benson-Manica" <at***@otaku.freeshell.orgwrote in message
news:eo**********@chessie.cirr.com...
Clark S. Cox III <cl*******@gmail.comwrote:
>If I pass NULL to strlen, then it was a mistake

On the contrary, I think it's certainly possible to imagine code that
could profitably take advantage of the hypothetical ability of
strlen() to deal reasonably with a null pointer. Given how the
language is defined, of course, it's a mistake.
>only server to mask that error, and potentially hide it until my product
was already released. If strlen attempts to dereference NULL then it
will interrupt the program (on every implementation that I use, and yes,
I test this assumption before relying on it on every platform for which
I code).

If you find a platform for which your assumption does not hold, what
are your plans for testing your code?
I think Clark's comments are reasonable. It is no different than generously
using assert(), except he is relying on the [hardware/OS] platform to check
the assertions.
Jan 11 '07 #12

"Clark S. Cox III" <cl*******@gmail.comwrote in message
news:12*************@corp.supernews.com...
Barry wrote:
I thought (perhaps mistakenly) the question was trying to be more
thoughtful and the OP meant to ask something like:

Why doesn't strlen check for a NULL pointer and return.

If I pass NULL to strlen, then it was a mistake; simply returning would
only server to mask that error, and potentially hide it until my product
was already released. If strlen attempts to dereference NULL then it
will interrupt the program (on every implementation that I use, and yes,
I test this assumption before relying on it on every platform for which
I code).

I prefer my errors to be caught *before* release as much as possible.
Your inability to read an entire message or thread and reply is
laughable.
Jan 11 '07 #13

"Clark S. Cox III" <cl*******@gmail.comwrote in message
news:12*************@corp.supernews.com...
Barry wrote:
I thought (perhaps mistakenly) the question was trying to be more
thoughtful and the OP meant to ask something like:

Why doesn't strlen check for a NULL pointer and return.

If I pass NULL to strlen, then it was a mistake; simply returning would
only server to mask that error, and potentially hide it until my product
was already released. If strlen attempts to dereference NULL then it
will interrupt the program (on every implementation that I use, and yes,
I test this assumption before relying on it on every platform for which
I code).

I prefer my errors to be caught *before* release as much as possible.

--
Clark S. Cox III
cl*******@gmail.com
The NEXT time you choose to pick a sentence out of context you
should properly apologize in the same forum.
Jan 11 '07 #14
Christopher Benson-Manica wrote:
Clark S. Cox III <cl*******@gmail.comwrote:
>If I pass NULL to strlen, then it was a mistake

On the contrary, I think it's certainly possible to imagine code that
could profitably take advantage of the hypothetical ability of
strlen() to deal reasonably with a null pointer. Given how the
language is defined, of course, it's a mistake.
Other than assert'ing that the parameter is non-NULL, what would you
consider a reasonable way for strlen to deal with NULL?
only server to mask that error, and potentially hide it until my product
was already released. If strlen attempts to dereference NULL then it
will interrupt the program (on every implementation that I use, and yes,
I test this assumption before relying on it on every platform for which
I code).

If you find a platform for which your assumption does not hold, what
are your plans for testing your code?
If I find a platform where that assumption doesn't hold, then, as I said
above, I won't rely on it. The last platform on which I did any
extensive coding that didn't, upon a read from NULL, cause programs to
immediately crash, interrupt, drop into a debugger, etc. was the old
(i.e. pre MacOSX, pre-VM) MacOS. However, even there, it was a simple
matter to configure the debugger to watch for access to that memory
location.
--
Clark S. Cox III
cl*******@gmail.com
Jan 11 '07 #15
Barry wrote:
"Clark S. Cox III" <cl*******@gmail.comwrote in message
news:12*************@corp.supernews.com...
Barry wrote:
I thought (perhaps mistakenly) the question was trying to be more
thoughtful and the OP meant to ask something like:
>
Why doesn't strlen check for a NULL pointer and return.
If I pass NULL to strlen, then it was a mistake; simply returning would
only server to mask that error, and potentially hide it until my product
was already released. If strlen attempts to dereference NULL then it
will interrupt the program (on every implementation that I use, and yes,
I test this assumption before relying on it on every platform for which
I code).

I prefer my errors to be caught *before* release as much as possible.

The NEXT time you choose to pick a sentence out of context you
should properly apologize in the same forum.
What sentence did I take out of context? (I don't mean to sound snarky,
I am honestly confused as to how you think that I misconstrued what you
said). You stated what you thought the OP meant to ask, and I answered
that question.

Additionally, I am not sure why you responded to me twice.

--
Clark S. Cox III
cl*******@gmail.com
Jan 11 '07 #16
Clark S. Cox III <cl*******@gmail.comwrote:
Other than assert'ing that the parameter is non-NULL, what would you
consider a reasonable way for strlen to deal with NULL?
To me, it wouldn't strike me as unreasonable for strlen(NULL) to
return 0. I presume the reasons that it doesn't are a) performance, and
b) not all the other str* functions could have reasonable behavior
when passed NULL, so none of them do.
If I find a platform where that assumption doesn't hold, then, as I said
above, I won't rely on it. The last platform on which I did any
extensive coding that didn't, upon a read from NULL, cause programs to
immediately crash, interrupt, drop into a debugger, etc. was the old
(i.e. pre MacOSX, pre-VM) MacOS. However, even there, it was a simple
matter to configure the debugger to watch for access to that memory
location.
That's reasonable, I was just curious.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
Jan 11 '07 #17

Barry schrieb:
Why doesn't strlen check for a NULL pointer and return.
Return WHAT?
Perhaps 0, so the caller is led to believe that there is an empty
string?
Or -1. No wait, this is an unsigned return type, so it couldn't.
How about 999999999?
Surely, nobody ever has such a long string?

Jan 11 '07 #18
Barry <ba****@nullhighstream.netwrote:
<snip>
>
Why doesn't strlen check for a NULL pointer and return.
C99, 7.21.6.3-3: "The strlen function returns the number of characters
that precede the terminating null character."

I don't think it's possible to return any value such that it satisfies
this condition if NULL is passed to the function. The return value is
size_t so using negative values is not possible.

--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)

Jan 11 '07 #19
David T. Ashley wrote:
<sa*****@yahoo.co.inwrote in message
news:11*********************@o58g2000hsb.googlegro ups.com...
>Hi Everyone,

I tried the following program unit in Microsoft Visual c++ 6.0 and the
program caused unexpected behavior,

#include <stdio.h>
#include <string.h>

int main()
{
char *p;
p = NULL;
printf("%d\n",strlen(p));
}

Is it that strlen function can't handle NULL pointers?

You're apparently a new programmer, so let me add this:

A NULL pointer and a string of length zero are not the same thing.

A NULL pointer traditionally has the value of 0, which is usually an
unsuitable pointer; but in any case it is a reserved value defined to be a
non-functional pointer.

A string of length 0 has a non-NULL pointer, but the area of memory that is
pointed to has its first byte as 0.

The two are very different.
Good description.

I'll add to this by stating that folks often conflate the null pointer
and the null (or NUL, if that's how you roll) byte at the end of a C-string.

I can see that one might assume that a "null string" and a "null pointer
to an empty string" would have correspondence. The term "null" is used
in quite an overloaded manner in casual conversation, and it can be easy
to conflate the two.
Jan 11 '07 #20

<ma**********@pobox.comwrote in message
news:11**********************@i39g2000hsf.googlegr oups.com...
>
sam_...@yahoo.co.in wrote:
> Is it that strlen function can't handle NULL pointers?

Strlen expects a string as an argument. Is a NULL pointer a string?
(Hint: this is a rhetorical question).
thats a bit silly really, it's just a matter of implementation
I dont know exactly what the standard says, but at least it was decided at
some point that strcpy does not accept NULL or at the very least does not
have to. They might as well just have chosen to let the string functions do
nothing when being passed NULL.

Or take this example:
char *p = NULL;
free(p);

is p a valid pointer returned from malloc,calloc or realloc? well no, but
for free it was decided to let it accept that
Jan 11 '07 #21
"David T. Ashley" <dt*@e3ft.comwrites:
[...]
A NULL pointer and a string of length zero are not the same thing.
The phrase "NULL pointer" is just *slightly* misleading. The correct
term is "null pointer".

NULL is a macro defined in <stddef.hand several other standard
headers. It expands to an implementation-defined "null pointer
constant". A "null pointer constant" and a "null pointer" are two
very different things; the former is a construct that can appear in a
C source file, and the latter is a value that can exist during
execution of a program. You typically use a null pointer constant to
obtain a null pointer at run time (which is why the name "null pointer
constant" contains the phrase "null pointer"), but it can be important
to keep the distinction in mind.
A NULL pointer traditionally has the value of 0, which is usually an
unsuitable pointer; but in any case it is a reserved value defined
to be a non-functional pointer.
A literal 0 is by definition a null pointer constant. A null pointer
value may or may not be represented as all-bits-zero. Section 5 of
the comp.lang.c FAQ, <http://www.c-faq.com/>, covers this very well.

[...]

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 11 '07 #22
"Clark S. Cox III" <cl*******@gmail.comwrote in message
news:12*************@corp.supernews.com...
Other than assert'ing that the parameter is non-NULL, what would you
consider a reasonable way for strlen to deal with NULL?
strlen(NULL) == 0 on some implementations. That might be considered
reasonable, depending on who you ask.
If I find a platform where that assumption doesn't hold, then, as I
said
above, I won't rely on it. The last platform on which I did any
extensive coding that didn't, upon a read from NULL, cause programs to
immediately crash, interrupt, drop into a debugger, etc. was the old
(i.e. pre MacOSX, pre-VM) MacOS. However, even there, it was a simple
matter to configure the debugger to watch for access to that memory
location.
This is actually near and dear to my heart, because I wrote my first C
program on AIX. All of the str* functions failed silently when passed
NULL, so I grew to rely on that behavior. When I then tried running the
same code on Linux, I ended up spending hours adding in NULL checks
because glibc would segfault, unlike AIX's libc. It was an eye-opening
experience for me about assuming what's portable in C. Luckily for me,
I encountered this on my very first program (okay, so my "hello world"
used sockets and Motif, but still...) so I didn't let that "whatever
works on my system should work anywhere" mentality that many C novices
seem to develop.

I'd prefer a happy medium -- a debug build that assert()ed whenever I
did something stupid, but also a release build that would make an
attempt to do something sane and thus not crash on the user...

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking
--
Posted via a free Usenet account from http://www.teranews.com

Jan 11 '07 #23
Serve Laurijssen wrote:
>
<ma**********@pobox.comwrote in message
news:11**********************@i39g2000hsf.googlegr oups.com...

sam_...@yahoo.co.in wrote:
Is it that strlen function can't handle NULL pointers?
Strlen expects a string as an argument. Is a NULL pointer a string?
(Hint: this is a rhetorical question).

thats a bit silly really, it's just a matter of implementation
No, a matter of definition.
I dont know exactly what the standard says, but at least it was
decided at some point that strcpy does not accept NULL or at the very
least does not have to.
We are discussing strlen(). The standard wording for that has been
posted. Some other string functions may generate a different discussion.
They might as well just have chosen to let
the string functions do nothing when being passed NULL.
What does "do nothing" mean to you? strlen() has to return a value, so
"nothing" not really an option.
Or take this example:
char *p = NULL;
free(p);

is p a valid pointer returned from malloc,calloc or realloc? well no,
but for free it was decided to let it accept that

free() does not return a value, so it can indeed "do nothing".


Brian
Jan 11 '07 #24
ma**********@pobox.com writes:
sam_...@yahoo.co.in wrote:
> Is it that strlen function can't handle NULL pointers?

Strlen expects a string as an argument. Is a NULL pointer a string?
(Hint: this is a rhetorical question).
No, strlen expected a pointer to a string as an argument. (And a null
pointer does not point to a string.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 11 '07 #25
# Is it that strlen function can't handle NULL pointers?

No, it doesn't. You can define your own string length function which does.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
So basically, you just trace.
Jan 11 '07 #26
On Thu, 11 Jan 2007 15:05:44 -0600, "Stephen Sprunk"
<st*****@sprunk.orgwrote:
>"Clark S. Cox III" <cl*******@gmail.comwrote in message
news:12*************@corp.supernews.com...
>Other than assert'ing that the parameter is non-NULL, what would you
consider a reasonable way for strlen to deal with NULL?

strlen(NULL) == 0 on some implementations. That might be considered
reasonable, depending on who you ask.
>If I find a platform where that assumption doesn't hold, then, as I
said
above, I won't rely on it. The last platform on which I did any
extensive coding that didn't, upon a read from NULL, cause programs to
immediately crash, interrupt, drop into a debugger, etc. was the old
(i.e. pre MacOSX, pre-VM) MacOS. However, even there, it was a simple
matter to configure the debugger to watch for access to that memory
location.

This is actually near and dear to my heart, because I wrote my first C
program on AIX. All of the str* functions failed silently when passed
NULL, so I grew to rely on that behavior. When I then tried running the
same code on Linux, I ended up spending hours adding in NULL checks
because glibc would segfault, unlike AIX's libc. It was an eye-opening
experience for me about assuming what's portable in C. Luckily for me,
I encountered this on my very first program (okay, so my "hello world"
used sockets and Motif, but still...) so I didn't let that "whatever
works on my system should work anywhere" mentality that many C novices
seem to develop.

I'd prefer a happy medium -- a debug build that assert()ed whenever I
did something stupid, but also a release build that would make an
attempt to do something sane and thus not crash on the user...

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking
The C library I'm using has 2 versions, a debug and a release one.
When I'm developing I use the debug library. It does

size_t strlen(const char *s)
{
assert(s != NULL);
...
}

Jim
Jan 12 '07 #27
>Other than assert'ing that the parameter is non-NULL, what would you
>consider a reasonable way for strlen to deal with NULL?

To me, it wouldn't strike me as unreasonable for strlen(NULL) to
return 0.
To me, it wouldn't strike me as unreasonable for strlen(NULL) to
run:
while(1) {
abort();
}

The bug gets identified quickly. However, this is not recommended
for safety-critical software *in production* such as flight control,
where "crash" has a very different meaning.
>I presume the reasons that it doesn't are a) performance, and
b) not all the other str* functions could have reasonable behavior
when passed NULL, so none of them do.
Some str* functions *DO* have defined behavior when passed NULL
instead of a string. Example: the first argument of strtok().
Jan 12 '07 #28
On Thu, 11 Jan 2007 23:09:37 -0000, SM Ryan
<wy*****@tango-sierra-oscar-foxtrot-tango.fake.orgwrote:
># Is it that strlen function can't handle NULL pointers?

No, it doesn't. You can define your own string length function which does.
Yes but you can't call it strlen if it has external linkage since that
name is reserved.
Remove del for email
Jan 12 '07 #29
On 11 Jan 2007 04:38:18 -0800, sa*****@yahoo.co.in wrote:
>Hi Everyone,

I tried the following program unit in Microsoft Visual c++ 6.0 and the
program caused unexpected behavior,
On the contrary, the program did exactly what you should have
expected.
>
#include <stdio.h>
#include <string.h>

int main()
{
char *p;
p = NULL;
printf("%d\n",strlen(p));
This statement invokes undefined behavior. Anything your program does
at this point is not unexpected or perhaps it should be phrased that
at this point you are no longer entitled to have any expectations.
>}

Is it that strlen function can't handle NULL pointers?
Yes but. Even if some compiler included a strlen function in its run
time library that did handle NULL pointers, the standard still states
the behavior is undefined.
Remove del for email
Jan 12 '07 #30
ma**********@pobox.com wrote:
sam_...@yahoo.co.in wrote:
> Is it that strlen function can't handle NULL pointers?

Strlen expects a string as an argument. Is a NULL pointer a string?
(Hint: this is a rhetorical question).
To be slightly more accurate, strlen expects a pointer to a
string. Does NULL point to a string.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
Jan 12 '07 #31
On Fri, 12 Jan 2007 01:25:22 -0000, go***********@burditt.org (Gordon
Burditt) wrote:
>>Other than assert'ing that the parameter is non-NULL, what would you
consider a reasonable way for strlen to deal with NULL?

To me, it wouldn't strike me as unreasonable for strlen(NULL) to
return 0.

To me, it wouldn't strike me as unreasonable for strlen(NULL) to
run:
while(1) {
abort();
}

The bug gets identified quickly. However, this is not recommended
for safety-critical software *in production* such as flight control,
where "crash" has a very different meaning.
I disagree. It should be recommended.

That's because strlen(NULL) results in undefined behavior, and you
should have caught such an error during verification, way before the
software gets into *production* (especially with safety-critical
software).

If not, then what you are saying is that it's better to rely on the
results of undefined behavior of strlen(NULL) and all it's perverse
consequences than to rely on the "crash"?

Best regards
--
jay
Jan 12 '07 #32
Ingo Menger <qu*********@consultant.comwrote:
Why doesn't strlen check for a NULL pointer and return.
Return WHAT?
Perhaps 0, so the caller is led to believe that there is an empty
string?
That would be the best option. errno could also be set, but that
would really complicate matters for most strlen() clients.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
Jan 12 '07 #33
In article <eo*********@news6.zwoll1.ov.home.nl"Serve Laurijssen" <se*@n.tkwrites:
....
I dont know exactly what the standard says, but at least it was decided at
some point that strcpy does not accept NULL or at the very least does not
have to. They might as well just have chosen to let the string functions do
nothing when being passed NULL.
How about
strcmp(NULL, "")
?
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Jan 12 '07 #34
"jaysome" <ja*****@hotmail.comwrote in message
news:b4********************************@4ax.com...
On Fri, 12 Jan 2007 01:25:22 -0000, go***********@burditt.org (Gordon
Burditt) wrote:
>>The bug gets identified quickly. However, this is not recommended
for safety-critical software *in production* such as flight control,
where "crash" has a very different meaning.

I disagree. It should be recommended.

That's because strlen(NULL) results in undefined behavior, and you
should have caught such an error during verification, way before the
software gets into *production* (especially with safety-critical
software).
One can never test every possible condition in complex real-world
software, and the consequences of your validation being incomplete are
too severe to risk a crash no matter how sure you are you got it right.
Trying to do _something_ reasonable at least has the _chance_ of saving
lives; crashing leaves no chance at all. Deliberately choosing to kill
people is likely to bankrupt you, if not put you in jail.

Pedantism is for those who don't have to face the consequences, or those
whose work doesn't matter.
If not, then what you are saying is that it's better to rely on the
results of undefined behavior of strlen(NULL) and all it's perverse
consequences than to rely on the "crash"?
Yes.

Imagine a hypothetical 911* call center. Now, say there's a bug that
causes the agents' phones to crash randomly due to trapping on
strlen(NULL). It's one thing for that to be an accident, in which case
the phone vendor is likely to only face a few million dollars (per
victim) in fines and civil suits, but if it came out that the crash was
deliberate when there was the option of handling the error without
hanging up on someone who was being raped or assaulted, well, let's just
say juries wouldn't be very sympathetic to those responsible.

(And this isn't such a hypothetical example. I've seen it actually
happen to two different vendors, though NDAs prevent me from saying who
or when.)

S

* For those outside the US, replace with your local emergency services
number, e.g. 112 in Europe.

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking
--
Posted via a free Usenet account from http://www.teranews.com

Jan 12 '07 #35

"Dik T. Winter" <Di********@cwi.nlwrote in message
news:JB********@cwi.nl...
In article <eo*********@news6.zwoll1.ov.home.nl"Serve Laurijssen"
<se*@n.tkwrites:
...
I dont know exactly what the standard says, but at least it was decided
at
some point that strcpy does not accept NULL or at the very least does
not
have to. They might as well just have chosen to let the string functions
do
nothing when being passed NULL.

How about
strcmp(NULL, "")
thats a good one. My intuition would say that they would compare unequal.
But thats impossible because would strcmp return <0 or >0? Now I see why it
was decided to not let the string functions have defined behaviour when
being passed NULL.
Jan 12 '07 #36
"Serve Laurijssen" <se*@n.tkwrote in message
news:eo**********@news2.zwoll1.ov.home.nl...
"Dik T. Winter" <Di********@cwi.nlwrote in message
news:JB********@cwi.nl...
>How about
strcmp(NULL, "")

thats a good one. My intuition would say that they would compare
unequal.
Interesting. My intuition would be that -- assuming that the call
doesn't segfault -- it'd compare equal. That's the more logical thing
to me, since novice programmers don't see a difference between NULL and
"", and certain things get a lot simpler if you require that to be true.

The rest of the str* functions fall into line pretty well once you take
that stand, which is convenient (if you choose to define any of them for
NULL params).
But thats impossible because would strcmp return <0 or >0? Now I see
why it was decided to not let the string functions have defined
behaviour
when being passed NULL.
My guess is that, like many other things in C, the behavior prior to C89
was divergent, so ANSI decided it was better left undefined to avoid
forcing implementors to change their code.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking
--
Posted via a free Usenet account from http://www.teranews.com

Jan 12 '07 #37

"Stephen Sprunk" <st*****@sprunk.orgwrote in message
news:45**********************@free.teranews.com...
"Serve Laurijssen" <se*@n.tkwrote in message
news:eo**********@news2.zwoll1.ov.home.nl...
>"Dik T. Winter" <Di********@cwi.nlwrote in message
news:JB********@cwi.nl...
>>How about
strcmp(NULL, "")

thats a good one. My intuition would say that they would compare
unequal.

Interesting. My intuition would be that -- assuming that the call doesn't
segfault -- it'd compare equal. That's the more logical thing to me,
since novice programmers don't see a difference between NULL and "", and
certain things get a lot simpler if you require that to be true.
So then this code would be accepted too:

struct Struct *astruct = ""; // since NULL is the same as ""

if (strcmp((const char *)astruct, "") == 0)
{
// etc
}

I dont know about you, but it's getting pretty scary to me :)

Jan 12 '07 #38
"Serve Laurijssen" <se*@n.tkwrote in message
news:eo**********@news6.zwoll1.ov.home.nl...
"Stephen Sprunk" <st*****@sprunk.orgwrote in message
>Interesting. My intuition would be that -- assuming that the call
doesn't segfault -- it'd compare equal. That's the more logical
thing
to me, since novice programmers don't see a difference between
NULL and "", and certain things get a lot simpler if you require that
to be true.

So then this code would be accepted too:

struct Struct *astruct = ""; // since NULL is the same as ""
Not the same in that sense, no. Saying strcmp(NULL,"") returns equality
is very different than saying NULL=="". The latter is necessarily
false; the former is allowed by the C standard since the behavior is
undefined.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking
--
Posted via a free Usenet account from http://www.teranews.com

Jan 13 '07 #39

"Stephen Sprunk" <st*****@sprunk.orgwrote in message
news:45**********************@free.teranews.com...
"Serve Laurijssen" <se*@n.tkwrote in message
news:eo**********@news6.zwoll1.ov.home.nl...
>struct Struct *astruct = ""; // since NULL is the same as ""

Not the same in that sense, no. Saying strcmp(NULL,"") returns equality
is very different than saying NULL=="". The latter is necessarily false;
the former is allowed by the C standard since the behavior is undefined.
struct Struct *astruct = NULL;

suddenly this becomes a valid parameter to strcmp comparing equal to ""
Jan 13 '07 #40
On Sat, 13 Jan 2007 10:03:08 +0100, "Serve Laurijssen" <se*@n.tk>
wrote:
>
"Stephen Sprunk" <st*****@sprunk.orgwrote in message
news:45**********************@free.teranews.com.. .
>"Serve Laurijssen" <se*@n.tkwrote in message
news:eo**********@news6.zwoll1.ov.home.nl...
>>struct Struct *astruct = ""; // since NULL is the same as ""

Not the same in that sense, no. Saying strcmp(NULL,"") returns equality
is very different than saying NULL=="". The latter is necessarily false;
the former is allowed by the C standard since the behavior is undefined.

struct Struct *astruct = NULL;

suddenly this becomes a valid parameter to strcmp comparing equal to ""
It does not happen so suddenly. If you have some contrived code like
the following:

#include <string.h>
int main(void)
{
struct Struct *astruct = NULL;
(void)strcmp(astruct,"");
return 0;
}

then it should not even compile, under Standard C.

The Standard C function strcmp() has a prototype whose first argument
is of type const char *. The above code passes an object of type
struct Struct * as its first argument to strcmp(). The types const
char * and struct Struct * are not compatible (meaning that there is
no implicit conversion between the two), and a Standard C-compliant
compiler MUST reject such an incompatibility.

Some might think that a simple "fix" is to explicitly convert astruct
to type const char * or just char *:

#include <string.h>
int main(void)
{
struct Struct *astruct = NULL;
(void)strcmp((char *)astruct,"");
return 0;
}

Never, ever, do this type of thing under these circumstances.
Silencing compiler warnings or errors with explicit casts can get you
into real, terrible, trouble.

Best regards
--
jay
Jan 13 '07 #41
"Stephen Sprunk" <st*****@sprunk.orgwrote:
"Serve Laurijssen" <se*@n.tkwrote in message
"Dik T. Winter" <Di********@cwi.nlwrote in message
How about
strcmp(NULL, "")
thats a good one. My intuition would say that they would compare
unequal.

Interesting. My intuition would be that -- assuming that the call
doesn't segfault -- it'd compare equal. That's the more logical thing
to me, since novice programmers don't see a difference between NULL and
"", and certain things get a lot simpler if you require that to be true.
Database developers burst out in tears.

FYI, there's a world of difference between "there's no valid data for
this item (yet)" and "the valid data for this item is blank".

Richard
Jan 15 '07 #42
"Richard Bos" <rl*@hoekstra-uitgeverij.nlwrote in message
news:45****************@news.xs4all.nl...
"Stephen Sprunk" <st*****@sprunk.orgwrote:
>"Serve Laurijssen" <se*@n.tkwrote in message
"Dik T. Winter" <Di********@cwi.nlwrote in message
How about
strcmp(NULL, "")

thats a good one. My intuition would say that they would compare
unequal.

Interesting. My intuition would be that -- assuming that the call
doesn't segfault -- it'd compare equal. That's the more logical
thing
to me, since novice programmers don't see a difference between
NULL and "", and certain things get a lot simpler if you require that
to be true.

Database developers burst out in tears.

FYI, there's a world of difference between "there's no valid data for
this item (yet)" and "the valid data for this item is blank".
If the caller cares about the distinction, they could always use == to
test the two arguments before passing them to strcmp(). Presently, one
must test both arguments against NULL anyways before calling strcmp()
because failing to do so may cause a crash. What I suggest reduces the
amount of work for most folks and makes it no worse for the rest.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking
--
Posted via a free Usenet account from http://www.teranews.com

Jan 15 '07 #43
In article <45**********************@free.teranews.com>,
Stephen Sprunk <st*****@sprunk.orgwrote:
>Presently, one
must test both arguments against NULL anyways before calling strcmp()
because failing to do so may cause a crash.
This is only needed if there is some possibility that one of them
might be null, which is almost never the case in my code. And if I
were writing a library function that passed one of its arguments to
strcmp(), then I would only test it if the function was supposed to
accept null; if not then I would leave it to strcmp() to crash.

In effect I rely on something the C standard doesn't guarantee: that
strcmp() *will* crash if I make the mistake of giving it a null
argument, rather than producing some result. This is a
quality-of-implementation issue.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Jan 15 '07 #44
CBFalconer wrote:
ma**********@pobox.com wrote:
>sam_...@yahoo.co.in wrote:
>> Is it that strlen function can't handle NULL pointers?
Strlen expects a string as an argument. Is a NULL pointer a string?
(Hint: this is a rhetorical question).

To be slightly more accurate, strlen expects a pointer to a
string. Does NULL point to a string.
No...but a pointer to a NUL byte points to a zero-length
string... ;-)

--
+----------------------------------------------------------------+
| Charles and Francis Richmond richmond at plano dot net |
+----------------------------------------------------------------+
Jan 18 '07 #45

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: lasek | last post by:
Hi all, a simple question, look at this code below: char acName="Claudio"; unsigned int uiLen; uiLen=strlen(acName); printf("Length of acName variable %u",uiLen); //uiLen >>>> 7
8
by: A. Anderson | last post by:
Howdy everyone, I'm experiencing a problem with a program that I'm developing. Take a look at this stack report from GDB - #0 0xb7d782a3 in strlen () from /lib/tls/i686/cmov/libc.so.6 #1 ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.