0

I recently started learning c++ and I have a problem with implementing my own string class with string concatenation. When the strings are added together, an error appears in debugging : <incomplete sequence \331> I checked on many lines and noticed that the program works fine when the line is short , but stops working at all with long lines I think I messed up my memory somewhere , but I can't find where I will be very glad of any help

#include <iostream>
#include <string>
#include <string.h>

using namespace std;

class String
{
private:
    char *data;
    int length;

public:
    ~String();
    String(){};
    String(char*);

    int get_length(){return length;}
    void add_stick();
    String operator+(const String &);
    void show();
    friend istream &operator>>(istream &, String &);
    friend ostream &operator<<(ostream &, const String &);
};

void String::add_stick()
{
    for (int i = 1; i <= length; i++)
    {
        if (i % 2 == 0)
        {
            data[i-1] = '_';
        }
    }
}

String::String(char* str)
{
    length = strlen(str);
    data = str;
}

void String::show()
{
    cout << data;
}

String String::operator+(const String &str)
{
    char* tmp;
    int len = length + str.length;
    tmp = new char (len);
    for (int i = 0; i < this->length; i++)
    {
        tmp[i] = this->data[i];
    }

    int j = 0;
    for (int i = this->length; i < len; i++)
    {
        tmp[i] = str.data[j];
        j++;
    }

    String koko(tmp);
    tmp = nullptr;
    delete[] tmp;
    return koko;
}

String::~String()
{
    data = nullptr;
    delete[] data;
    length = 0;
}

istream &operator>>(istream &in, String &str)
{
    str.data = new char[1000];
    in.getline(str.data, 1000);
    str.length = strlen(str.data);
    return in;
}

ostream &operator<<(ostream &out, const String &str)
{
    out << str.data;

    return out;
}

int main()
{
    String s[5];
    cin >> s[0] >> s[1] >> s[2] >> s[3] >> s[4];

    String str (s[0] + s[1] + s[2] + s[3] + s[4]);

    str.add_stick();

    cout << str;
}
den229x
  • 3
  • 1

1 Answers1

1

There are a lot of things wrong with your code.

  • Where is your operator=? You appear to have violated the Rule of Three. This is a massive memory bug.
  • for (int i = 1; i <= length; i++) if (i % 2 == 0) seems like a weird way to write for (int i = 2; i <= length; i+=2). This works fine, it's just weird.
  • operator+ does not allocate enough bytes for a null terminator, so all operations after that will read past the end of the buffer. This is a massive memory bug.
  • String(char* str) doesn't make a copy of the data, it assumes ownership of the pointer passed in. Which might work, except that operator+ constructs a String from tmp, and then deletes tmp, so now the String's data is gone. This is a massive memory bug.
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158