I was just writing simple code and then I saw something strange. The code is supposed to append a string to another string. The output from the new appended string outputs not only the correct appended string, but it also adds every time four time the number 2 and I don't understand why. I thought it was some memory leak I overlooked or something like that, but there it outputs every time the same four numbers.
Code:
#include <iostream>
using namespace std;
unsigned int getStrSize(const char* string)
{
unsigned int size = 0;
while (string[size] != '\0')
{
size++;
}
return size;
}
int main()
{
const char* bla1 = "hello";
const char* bla2 = " blaah";
int size1 = getStrSize(bla1);
int size2 = getStrSize(bla2);
int size12 = size1 + size2;
char* bla12 = new char[size12];
for (int i = 0; i < size1; i++)
{
bla12[i] = bla1[i];
}
for (int i = 0; i < size2; i++)
{
bla12[i + size1] = bla2[i];
}
char* blaNew = bla12;
cout << bla1 << "\n";
cout << bla2 << "\n";
cout << bla12 << "\n";
cout << blaNew << "\n";
}
Outputs:
hello
blaah
hello blaah²²²²
hello blaah²²²²