Does strlen() always correctly report the number of char's in a pointer initialized string?

209 views Asked by At

As long as I use the char and not some wchar_t type to declare a string will strlen() correctly report the number of chars in the string or are there some very specific cases I need to be aware of? Here is an example:

char *something = "Report all my chars, please!";
strlen(something);
1

There are 1 answers

0
Some programmer dude On BEST ANSWER

What strlen does is basically count all bytes until it hits a zero-byte, the so-called null-terminator, character '\0'.

So as long as the string contains a terminator within the bounds of the memory allocated for the string, strlen will correctly return the number of char in the string.

Note that strlen can't count the number of characters (code points) in a multi-byte encoded string (like UTF-8). It will correctly return the number of bytes in the string though.