-3

I'm writing my version of string class and when I tried to overload + operator, destructor triggers a breakpoint while the program is performing

function:

String operator+(const String & s, const String & st)
{
    int k = s.len + st.len + 1;
    char* x = new char[k];
    x = s.str;
    for (int i = 0, j = k - st.len - 1; j < k; j++, i++)
    {
        x[j] = st.str[i];
    }
    return String(x);
}

destructor:

String::~String()
{
    delete[] str;
}

main:

int main()
{
    String x("cos");
    String y("cos");
    String z = x + y;
    std::cout << z;
}

thanks for help

Niyo
  • 21
  • 5
  • 5
    What do you mean "triggers a breakpoint"? I suspect what's actually happening is that the debug heap used by Visual Studio is detecting memory corruption caused by a double free, caused by violating the [Rule of Three](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). But I can't tell, because you haven't posted a [minimal reproducing example](https://stackoverflow.com/help/mcve) nor [fully described what you're experiencing](https://stackoverflow.com/help/how-to-ask). – Mooing Duck Mar 15 '19 at 18:11
  • 1
    You've almost got a good question here, but heed advice of @MooingDuck, and then edit the question if you wish. – thb Mar 15 '19 at 18:14
  • 1
    Your `operator=` and/or copy constructor for `String` are most likely wrong/missing. Make sure to follow the [rule of five](https://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)). – Max Langhof Mar 15 '19 at 18:16
  • *I'm writing my version of string class* -- Try this example: `{String s1("abc"); String s2=s1;}` -- Don't be surprised if this small program also has bugs, all due to not implementing the requisite functions (rule of 3, rule of 5). – PaulMcKenzie Mar 15 '19 at 20:01

2 Answers2

5

You allocate a chunk of memory with char* x = new char[k];, then immediately overwrite that pointer (leaking the memory) with x = s.str;. The for loop will then copy the characters of the 2nd String to the end of the first one, likely writing past the end of the memory allocated for that string, resulting in Undefined Behavior (the breakpoint when the debug build detects the problem).

You need to get rid of the assignment to x and copy the first String's characters into x similarly to how you do for the second String.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • Moreover one `char*` string is stored in two `String` classes. When both `String`s are destroyed we have an undefined behaviour which the OP might have reffered to as "trigger a breakpoint" - second destructor complains with debugger running. – Quimby Mar 15 '19 at 18:29
0

Change x = s.str; to strcpy(x, s.str);

x = s.str will overwrite the pointer and cause memory leak.

strcpy(x, s.str); will copy the content of s.str to x.