简体   繁体   English

C++ 字符 class function append

[英]C++ char class function append

void CMPT135_String::append(const CMPT135_String &s) /*12*/
{
    char *temp = new char[this->getLength()+1];

    int len = CMPT135_String::cstrlen(buffer);

    for (int i =0; i < len; i++)
        temp[i] = this->operator[](i);

    for (int i = 0; i < s.getLength()+1; i++)
        temp[len+i] = s[i];

    if(this->getLength() >0) 
        delete[] this->buffer;

    this->buffer = temp;
}

I have been working with this append() member function for a custom string class.我一直在使用这个append()成员 function 来获取自定义字符串 class。

The function works fine, but after it runs I get a popup window showing up: function 工作正常,但运行后我得到一个弹出窗口 window 出现:

Windows has triggered a breakpoint in CMPT135_Assignment1.exe. Windows 已触发 CMPT135_Assignment1.exe 中的断点。

This may be due to a corruption of the heap, which indicates a bug in Assignment1.exe or any of the DLLs it has loaded.这可能是由于堆损坏,这表明 Assignment1.exe 或其已加载的任何 DLL 中存在错误。

This may also be due to the user pressing F12 while CMPT135_Assignment1.exe has focus.这也可能是由于用户在 CMPT135_Assignment1.exe 具有焦点时按 F12。

The output window may have more diagnostic information. output window 可能有更多的诊断信息。

Please tell me what is going wrong with this.请告诉我这是怎么回事。

You are not allocating enough memory for the new buffer.您没有为新缓冲区分配足够的 memory。 You are only allocating enough memory to copy this->getLength() number of characters from this , there is no room to also copy s.getLength() number of characters from s into that new buffer, so your second loop is corrupting random memory past the end of the new buffer.您只分配了足够的 memory 以从中复制this->getLength()个字符,没有空间将s.getLength()个字符从s复制到this新缓冲区中,因此您的第二个循环正在破坏随机 memory超过新缓冲区的末尾。

Try something more like this instead:尝试更多类似的东西:

void CMPT135_String::append(const CMPT135_String &s) /*12*/
{
    int this_len = this->getLength();
    int s_len = s.getLength();
    int new_len = this_len + s_len;

    char *temp = new char[new_len + 1];

    for (int i = 0; i < this_len; ++i)
        temp[i] = this->operator[](i);

    for (int i = 0; i < s_len; i++)
        temp[this_len + i] = s[i];

    temp[new_len] = '\0';

    delete[] this->buffer;
    this->buffer = temp;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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