簡體   English   中英

在我定義的 class 中釋放分配的緩沖區 memory 的問題

[英]Issues with freeing up allocated buffer memory in my defined class

這是用於處理添加 MyString class 對象的方法。 一切運行良好,直到 delete [] buff - 語句。 使用視覺工作室社區

MyString MyString::operator + (const MyString &rhs) const {
    size_t buff_size{ std::strlen(this->str) + 1 };
    char *buff = new char[buff_size];

    strcpy_s(buff, buff_size, str);
    size_t noOfEls{ std::strlen(str) + std::strlen(rhs.str) + 1 }; // total length + null terminator
    strcat_s(buff, noOfEls, rhs.str);

    MyString temp{ buff };

    delete[] buff; // complier error here
    return temp;
}

因此,在我嘗試編寫一個非成員 function 這是 MyString class 的朋友並且 function 解決了任何錯誤之后,我終於在我的代碼中找到了問題。 我想知道我做對了什么,並發現分配的緩沖區 memory 實際上不足以存儲從右側參數(rhs 變量)傳入的數據。 這是固定代碼,delete [] buff 按預期工作正常。

MyString MyString::operator + (const MyString &rhs) const {
    size_t buff_size{ std::strlen(this->str) + std::strlen(rhs.str) + 1 };
    char *buff = new char[buff_size];

    strcpy_s(buff, buff_size, str);
    strcat_s(buff, buff_size, rhs.str);

    MyString temp{ buff };

    delete[] buff;
    return temp;
}

如果您仔細查看 buff_size 變量,您會發現我為當前對象(this)和傳入 rhs 對象(NB:加上 null 終止符)的長度分配了 memory,而不是初始代碼 I上面寫的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM