String’s Length—Andrzej Krzemieński

Save to:
Instapaper Pocket Readability

Today from the desk of Andrzej:

String's Length

by Andrzej Krzemieński

From the article:

Let’s start with a small test. Is the invariant expressed with the following assertion correct?

void test_length(std::string const& s)
{
  assert(s.length() == strlen(s.c_str()));
}

It is not; otherwise I wouldn’t be mentioning this in the post; but do you know why it is wrong? ...

Add a Comment

You must sign in or register to add a comment.

Comments (2)

0 0

marshall said on Mar 20, 2014 05:49 PM:

No, because the data managed by the string could contain a null character, and strlen just looks for a null.

Say the string contained 0x41 0x42 0x00 0x43 (which is "AB\0C").

s.length() == 4, but strlen(s.c_str()) == 2.
0 0

marshall said on Mar 20, 2014 08:47 PM:

... and I see, following the link, that you answered this question in your blog. Sorry for the noise.