简体   繁体   中英

C++ String Append Function Weird Behavior

I have an append function part of a string class I am working on, and something very strange happens upon usage. When I print out the appended string inside the function and then also in main , it works. But when I comment out the printing part inside the function and just leave the print in main , the output is some random character. Here is the code:

String.cpp:

void String::append(const String buf)
{
    char c[99];

    for (auto i = 0; i < this->length(); ++i) {
        c[i] = this->cstr()[i];
    }

    for (auto i = this->length(); i < (this->length() + buf.length() + 1); ++i) {
        c[i] = buf.cstr()[i - this->length()];
    }

    *this = c;
    printf("%s\n", *this); // if I comment this line out then the append function doesn't work properly
}

Main:

int main()
{
    String a = "Hello";
    String b = "Hi";
    a.append(b);
    printf("%s\n", a);
}

When both print functions are used, the output is this:

When only the print function in main is used:

What might be causing this? Thanks.


Edit:

Assignment operator:

String &String::operator=(char* buf) {
    _buffer = buf;
    return *this;
}

Constructor:

String::String(char* buf) : _buffer(buf), _length(0) {
    setLength();
}
char c[99];

is an array with automatic storage duration. Using a pointer to the first element (aka c ) after you leave the append() function is undefined behaviour.

Storing it via your assignment operator will not save the data or prevent it from beeing deleted.

In order to keep the data you either need to deal with dynamic allocation using new and delete (which will be some effort, think about constructors, destructors, assignments, copy-constructors/assignments) or you need to copy the data to your previously assigned buffer.

For ways to copy an array of chars see this question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM