0

私は最も単純なクラステキストを持っています:

class Text
{
    char* txt;
public:
    Text(const char*);
    Text(const Text&);
    ~Text();

    const Text operator+(const Text&) const;
};

と実装:

#include "text.h"

Text::~Text()
{
    delete[] this->txt;
}


Text::Text(const char* argText)
{
    txt = new char[strlen(argText)+1];
    strcpy(txt, argText);
}

Text::Text(const Text& other)
{
    txt = new char[strlen(other.txt)+1];
    strcpy(txt, other.txt);
}

const Text Text::operator+(const Text& other) const
{
    char* ttxt, *newLine;
    ttxt = new char[strlen(txt)+strlen(other.txt)+2];
    strcat(ttxt, this->txt);
    newLine = new char[2];
    newLine[0] = '\n';
    newLine[1] = '\0';
    strcat(ttxt, newLine);
    strcat(ttxt, other.txt);
    Text temp(ttxt);
    delete[] newLine;
    return temp;
}

そしてメイン:

#include "text.h"

int main()
{
    Text a("First text.");
    Text b("Second lol!!\n kthxbye!!!!!!!");
    Text c(a+b);
}

そして、プログラムが中断しますnewLine = new char[2];new char[5] のように増やしてみましたが、それでも中断します。私が受け取るメッセージは次のとおりです。

Windows は、prTextClass.exe でブレークポイントをトリガーしました。

これは、ヒープの破損が原因である可能性があります。これは、prTextClass.exe または読み込まれた DLL のバグを示しています...

4

3 に答える 3

2

Text::operator+ ie の thid 行だと思います

strcat(ttxt, this->txt);

間違っている

strcpy(ttxt, this->txt);

現在、strcpy のように ttxt から開始するのではなく、新しいランダムなメモリ片の最後に追加しています。

しかし、C++ でのより良い修正は、文字列を保持するために char* ではなく std::string を使用することです。これにより、メモリ割り当てが行われるため、これらの種類のエラーが発生しなくなります。

また、コメントで指摘されているように、削除されていない ttxt リークがあり、Text a = b; を処理するには operator= が必要です。

于 2012-08-01T18:38:56.197 に答える
2
const Text Text::operator+(const Text& other) const
{
    char* ttxt, *newLine;
    ttxt = new char[strlen(txt)+strlen(other.txt)+2];
    strcat(ttxt, this->txt);
 // ^^^^^^^^^^^^^^^^^^^^^^^^ This line is buggy
    newLine = new char[2];
    newLine[0] = '\n';
    newLine[1] = '\0';
    strcat(ttxt, newLine);
    strcat(ttxt, other.txt);
    Text temp(ttxt);
    // ....

ttxt = new char[strlen(txt)+strlen(other.txt)+2];配列の内容を初期化しないことに注意してください。したがって、strcat()が呼び出されると、文字列の末尾としてttxt最初の文字を検索するため、不明な位置で停止します。'\0'ttxt

に変更する必要があります

strcpy(ttxt, this->txt);
于 2012-08-01T18:39:25.390 に答える
0

あなたのブレークラインの前のstrcatはおそらく責任があるものです

おそらく、割り当てた後にtxttをnullにするか、strcatが追加され続けないようにする必要があります。すなわち。最初の文字が 0 バイトであることを確認してください。

于 2012-08-01T18:37:23.920 に答える