Returning a local object results in garbage, while returning the same object temporary works fine

Hello,

I'm currently implementing my own string class (just for training), but I'm experiencing some problems in my substr() method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
MyString MyString::substr(size_t position, size_t length)
{
    if (checkBounds() || length == 0)
    {
        return MyString();
    }

    char* tmp = new char[length + 1];

    memcpy(tmp, this->s + position, length);

    tmp[length] = STRING_ESCAPE;

    MyString result(tmp);

    delete[] tmp;
    tmp = nullptr;

    return result;
}


When I call this method and print the return value (I'm printing the char array actuallay, not the object itself), I receive complete garbage, which is carried out as a bunch of squares.

But when I return a temporary object return MyString(tmp), everything works fine. Initially i suspected this issue is associated to the delete[] operation, but commenting it out shows no effect.

The MyString constructor which is called is the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
MyString::MyString(const char* s)
{
    size_t length = this->strlen(s);

    this->sLength = length;

    this->s = new char[length + 1];

    for (size_t i = 0; i <= length; ++i)
    {
        this->s[i] = *s;

        ++s;
    }
}


So where is my mistake? Thank you!
Suppose I have MyString str("Hello"). When I call str.substr(0, 10). What will happen?
it returns an empty string, simply ""
Looks like you are creating the temporary just fine. The problem might be in your copy constructor. Can you post that for us? (if you have a move constructor, can you post that as well?)
Topic archived. No new replies allowed.