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

- 222,467
- 53
- 283
- 367
-
9Ask yourself: How should strlen() know where your string ends, if it's not null-terminated? – DevSolar Mar 10 '09 at 20:50
-
2Technically speaking, there is no such thing as a C string that is not NUL-terminated, because the NUL-Terminator is defined to be part of the C string :) – fredoverflow Oct 28 '11 at 16:37
-
Haev you considered consulting the documentation? – user207421 Sep 27 '20 at 03:22
-
If you know the buffer size, you might want to use [memchr](https://www.cplusplus.com/reference/cstring/memchr/) instead, which returns null pointer if no null terminator is found, or strnlen to cap the max size of string. – Phi Oct 23 '21 at 03:10
9 Answers
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.

- 41,555
- 36
- 141
- 182
-
19It can also cause demons to fly out your nose. http://catb.org/jargon/html/N/nasal-demons.html – Paul Tomblin Mar 10 '09 at 18:02
-
6
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.

- 53,214
- 7
- 75
- 105
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.

- 28,120
- 21
- 85
- 141
It is not defined. It causes undefined behavior which means anything can happen, most likely your program will crash.

- 8,750
- 7
- 50
- 67
It will return the number of characters encountered before '\0' is found.

- 83,345
- 10
- 45
- 66
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 :)

- 1,364
- 8
- 7
-
6correction, if he is lucky it will crash. You wouldn't want this type of error to go unnoticed :-P. – Evan Teran Mar 10 '09 at 18:05
man 3 strcspn
size_t strcspn(const char *s, const char *reject);
A length of colon delimited strings:
size_t len = strcspn(str, ":");
A length of comma delimited strings:
size_t len = strcspn(str, ",");
A length of tab delimited strings:
size_t len = strcspn(str, "\t");

- 2,485
- 4
- 26
- 36