簡體   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;
}

我一直在使用這個append()成員 function 來獲取自定義字符串 class。

function 工作正常,但運行后我得到一個彈出窗口 window 出現:

Windows 已觸發 CMPT135_Assignment1.exe 中的斷點。

這可能是由於堆損壞,這表明 Assignment1.exe 或其已加載的任何 DLL 中存在錯誤。

這也可能是由於用戶在 CMPT135_Assignment1.exe 具有焦點時按 F12。

output window 可能有更多的診斷信息。

請告訴我這是怎么回事。

您沒有為新緩沖區分配足夠的 memory。 您只分配了足夠的 memory 以從中復制this->getLength()個字符,沒有空間將s.getLength()個字符從s復制到this新緩沖區中,因此您的第二個循環正在破壞隨機 memory超過新緩沖區的末尾。

嘗試更多類似的東西:

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