Reputation:
Is strlen(const char *s)
defined when s
is not null-terminated, and if so, what does it return?
Upvotes: 30
Views: 41897
Reputation: 2532
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");
Upvotes: -3
Reputation: 28882
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.
Upvotes: 2
Reputation: 1364
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 :)
Upvotes: 0
Reputation: 54634
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.
Upvotes: 12
Reputation: 8836
It is not defined. It causes undefined behavior which means anything can happen, most likely your program will crash.
Upvotes: 1
Reputation: 84752
It will return the number of characters encountered before '\0' is found.
Upvotes: 0
Reputation: 42463
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.
Upvotes: 42