0

I'm learning C++ and creating a simple class, tstring, defined by:

  • n the number of characters in a string;
  • ntotal the total number of characters in the tstring;
  • p, pointer to a zone which contains the data.

Hence, this class is composed by a static part (n, ntotal and p) and by a dynamic part (the data itself).

I created three constructors :

*one without parameters; *one copy constructor; * one constructor which takes a C-string parameter.

I would like to be able to concatenate one tstring object with one C string, using for example the instructions:

tstring x("Hello), y;
y = x + " World";

To do this, I am overloading the + operator as a non-member function.

However, when executing the following commands, all runs fine :

tstring x, y;
tstring z = x + y;

But when executing the following ones, I get a "pointer being freed was not allocated" error :

tstring x, y;
tstring z;
z =  x + y;

I understand a little bit the logic behind that error but can not find a way to solve it.

Any help is welcome, thank you in advance!


You can find my implementation of the +operator:

tstring operator+ (const tstring& myTstring1, const tstring& myTstring2)
{
    tstring result;
    result.n = myTstring1.nutile + myTstring2.n;
    result.ntotal = myTstring1.ntotal + myTstring2.ntotal;
    result.p = new char[result.ntotal];
    for (int k = 0; k < maTstring1.n; ++k) {
        result.p[k] = maTstring1.p[k];
    }
    for (int l = maTstring1.n; l < maTstring2.n; ++l) {
       result.p[l] = maTstring2.p[l];
    }
    return result;
}

The constructor without parameter:

tstring::tstring(){
    ntotal = 10;
    n = 0;
    p = new char[ntotal];
}

And the destructor:

tstring::~tstring(){
    delete[] p;
}
filaton
  • 2,257
  • 17
  • 27
  • 1
    Sounds like you're missing a copy-assignment operator. http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three – Mike Seymour Feb 17 '15 at 09:07
  • 1
    Sounds like he's cocking it up by not using something sane like std::vector. He should learn the sane way to do it. – Puppy Feb 17 '15 at 09:09
  • the `operator+` function seems to have a lot of typoes, make sure you are copy-pasting code instead of typing it out. It would help to show the whole tstring class. – M.M Feb 17 '15 at 09:16
  • @Mike Seymour : What is needed here operator= or copy constructor? or both? – VolAnd Feb 17 '15 at 09:17
  • @VolAnd A copy-assignment operator (`operator=`), as I said. From the "all runs fine" example, it sounds like there's a working copy constructor. – Mike Seymour Feb 17 '15 at 09:20
  • Thanks. And link "What is The Rule of Three?" is also usefull – VolAnd Feb 17 '15 at 09:21
  • 1
    @Puppy: True, but it's also important to learn how copy semantics work, and writing your own dynamic array/string/whatever is a good learning exercise. – Mike Seymour Feb 17 '15 at 09:24

0 Answers0