-1

I came across a scenario where string concatenation is failing in C++. But I don't see a reason for it to fail.

Code sample is as below:

int main()
{

    std::string a;
    std::string b = "bbbbbbb";

    a.resize(10);

    for (int i = 0; i <= 5; i++) {
        a[i] = 'a';
    }

    a = a+b;

    printf("\n%s\n", a.c_str());
}

It is outputting aaaaaa.

I was expecting it to output aaaaaabbbbb. If I change a.resize(10); to a.resize(5); I am getting the expected output.

Would be helpful if someone could help me in understanding the behaviour?

jsaji
  • 900
  • 1
  • 15
  • 31
  • 1
    If string has 5 items size, writing to 6 items `int i = 0; i <= 5;` is undefined behaviour, isn't it ? – rafix07 Jul 16 '21 at 08:07

2 Answers2

2

In addition to the off-by-one error, after concatenation, the contents of a in main are:

aaaaa\0\0\0\0\0bbbbb

So: five 'a' bytes, then five zero bytes, then five 'b' bytes. The string is fifteen bytes long.

printf, like other C functions, doesn't know about this size, and instead takes the length of the string to be until the first zero byte. In your case, that is "aaaaa".

To print the entire string, use something like std::cout. If you're certain you want printf, it is also possible to pass a length to that with the %.*s specifier.

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
1
std::string a;
a.resize(10);

gives you a string of size 10 but whose content is undefined.

You set the first 5 character to something specific and append some more characters to the end. But characters 5-10 never get set to something.

In the execution you are seeing, these characters happen to be zero, but printf – as a C style function — considers the appearance of a null character the end of the string. Therefore it stops printing.

idmean
  • 14,540
  • 9
  • 54
  • 83
  • If I understand things correctly, the new characters _must_ be zero ("initialized to `CharT()`" per [here](https://en.cppreference.com/w/cpp/string/basic_string/resize)) so the content is not undefined - just unexpected. – Wander Nauta Jul 16 '21 at 08:17
  • @WanderNauta But `CharT` is `char` in this case and `char`'s constructor doesn't initialize to a specific value. Same as with `char a;`. `a` doesn't contain a specified value. – idmean Jul 16 '21 at 08:21