tags:

views:

1389

answers:

9

Is strlen(const char *s) defined when s is not null-terminated, and if so, what does it return?

+10  A: 

No, it is not defined. It may result in a memory access violation, as it will keep counting until it reaches the first memory byte whose value is 0.

Hosam Aly
It can also cause demons to fly out your nose. http://catb.org/jargon/html/N/nasal-demons.html
Paul Tomblin
+1  A: 

It will return the number of characters encountered before '\0' is found.

David Segonds
A: 

It is not defined. It causes undefined behavior which means anything can happen, most likely your program will crash.

FigBug
A: 

It is always defined.

It will return the length of the "string" until it reaches a byte with a null in it. Bad idea because this can cause a buffer overflow.

Daniel A. White
No, it's not defined. Once you start traversing beyond the space that was allocated for the string, either through malloc or on the stack/heap, the results are strictly undefined.
Paul Tomblin
+6  A: 

From the C99 standard:

The strlen function returns the number of characters that precede the terminating null character.

If there is no null character that means the result is undefined.

MSN
+2  A: 

Not really, and it will cause bad things.

Devin Jeanpierre
A: 

strlen() only works (does something useful) on null-terminated strings; you'll get an entirely undefined result if you pass in anything other than that. If you're lucky, it won't cause a crash :)

Nik
correction, if he is lucky it will crash. You wouldn't want this type of error to go unnoticed :-P.
Evan Teran
+1  A: 

If your string is not NUL terminated, the function will keep looking until it finds one.

If you are lucky, this will cause your program to crash.

If you are not lucky, you will get a larger than expected length back, with a lot of 'unexpected' values in it.

EvilTeach
+1  A: 

May be You need strnlen?

vitaly.v.ch
Unfortunately, this isn't part of standard C.
joveha