How does strlen()
work internally?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
strlen
usually works by counting the characters in a string until a\0
character is found. A canonical implementation would be:There is no inherent bug in the function, it works exactly as documented.
That's not to say it doesn't have problems, to wit:
\0
at the end, you may run into problems but technically, that's not a C string (a) and it's your own fault.\0
characters in your string but, again, it wouldn't be a C string in that case.But none of those are bugs, they're just consequences of a design decision.
See also this excellent article by Joel Spolsky where he discusses various string formats and their characteristics, including normal C strings, Pascal strings and the combination of the two, null terminated Pascal strings, though he has a more, shall we say, "colorful" term for them :-)
(a) A C string is defined as a series of non-terminator characters (ie, any other than
\0
) followed by that terminator. Hence this definition disallows both embedded terminators within the sequence and sequences without such a terminator.Or, putting it more succinctly (as per the ISO standard):