Is strlen(const char *s) defined when s is not null-terminated, and if so, what does it return?
-
9Ask yourself: How should strlen() know where your string ends, if it's not null-terminated?DevSolar– DevSolar2009-03-10 20:50:58 +00:00Commented Mar 10, 2009 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– fredoverflow2011-10-28 16:37:46 +00:00Commented Oct 28, 2011 at 16:37
-
Haev you considered consulting the documentation?user207421– user2074212020-09-27 03:22:51 +00:00Commented Sep 27, 2020 at 3:22
-
If you know the buffer size, you might want to use memchr instead, which returns null pointer if no null terminator is found, or strnlen to cap the max size of string.Phi– Phi2021-10-23 03:10:47 +00:00Commented Oct 23, 2021 at 3:10
Add a comment
|
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.
2 Comments
Paul Tomblin
It can also cause demons to fly out your nose. catb.org/jargon/html/N/nasal-demons.html
Engineer
That explains my aching nostrils.
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 Comment
Evan Teran
correction, if he is lucky it will crash. You wouldn't want this type of error to go unnoticed :-P.
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");
1 Comment
user207421
Doesn't answer the question in any way.