2

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);
lord.garbage
  • 5,884
  • 5
  • 36
  • 55
  • 2
    Be aware of non-null-terminated strings... (see http://stackoverflow.com/questions/631516/strlen-on-non-null-terminated-char-string) – G.Rassovsky Jun 23 '15 at 09:28
  • 1
    `"This would \0 go wrong"` – moffeltje Jun 23 '15 at 09:29
  • @G.Rassovsky: That wouldn't be a "string", would it. – Kerrek SB Jun 23 '15 at 09:29
  • 4
    This smells like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Are you debugging some issue and suspect that `strlen` does not operate correctly? – Frerich Raabe Jun 23 '15 at 09:31
  • @FrerichRaabe, no. :) The program which uses `strlen()` does it's job perfect. I just wanted to catch any possible corner cases. – lord.garbage Jun 23 '15 at 09:33
  • As long as there are no embedded zeros, e.g. from a non-ASCII character set and you haven't let the string go out of scope or accidentally corrupted its memory then yes you're fine. – Andy Brown Jun 23 '15 at 09:34
  • @AndyBrown No edge cases, like where you're trying to read a string outside your allocated memory? – Mr Lister Jun 23 '15 at 09:52

1 Answers1

4

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621