Is strlen(const char *s)
defined when s
is not null-terminated, and if so, what does it return?
views:
1389answers:
9No, 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.
It will return the number of characters encountered before '\0' is found.
It is not defined. It causes undefined behavior which means anything can happen, most likely your program will crash.
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.
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.
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 :)
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.