I was wondering how strlen is implemented.
What if the input string doesn't have a null terminator, namely the
'\0'?
Q: What if a tree growing in a forest is made of plastic?
A: Then it is not a tree, or at least, it is not growing.
If something someone else is calling a "string" does not have the
'\0' terminator, it is not a string, or at least, not a C string.
In C, the word "string" means "data structure consisting of zero
or more characters, followed by a '\0' terminator". No terminator,
no string.
Since strlen() requires a string, it may assume it gets one.
There are functions that work on "non-stringy arrays"; in particular,
the mem* functions -- memcpy(), memmove(), memcmp(), memset(),
memchr() -- but they take more than one argument. If you have an
array that always contains exactly 40 characters, and it is possible
that none of them is '\0' but you want to find out whether there
is a '\0' in those 40 characters, you can use memchr():
char *p = memchr(my_array, '\0', 40);
memchr() stops when it finds the first '\0' or has used up the
count, whichever occurs first. (It then returns a pointer to the
found character, or NULL if the count ran out.) The strlen()
function has an effect much like memchr() with an "infinite" count,
except that because the count is "infinite", it "always" finds the
'\0':
size_t much_like_strlen(const char *p) {
const char *q = memchr(p, '\0', INFINITY);
return q - p;
}
except of course C does not really have a way to express "infinity"
here. (You can approximate it with (size_t)-1, though.)