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²²²²
You're missing the nil:
#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 + 1; // notice +1
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];
}
bla12[size12 - 1] = '\0'; // terminate with nil
char* blaNew = bla12;
cout << bla1 << "\n";
cout << bla2 << "\n";
cout << bla12 << "\n";
cout << blaNew << "\n";
delete[] bla12; // Don't leak memory
delete[] blaNew; //
}
Better yet consider using standard library functions:
#include <cstring>
#include <iostream>
int main() {
const char* bla1 = "hello";
const char* bla2 = " blaah";
auto const size1 = std::strlen(bla1);
auto const size2 = std::strlen(bla2);
auto const size12 = size1 + size2 + 1;
char* bla12 = new char[size12];
std::strcpy(bla12, bla1);
std::strcat(bla12, bla2);
char* blaNew = bla12;
std::cout << bla1 << "\n";
std::cout << bla2 << "\n";
std::cout << bla12 << "\n";
std::cout << blaNew << "\n";
delete[] bla12;
delete[] blaNew;
}