0

valgrindを使用した次の関数でサイズの読み取りが無効です。理由はよくわかりませんが、誰か助けていただければ幸いです。私が言えることから、それは問題なく動作しますが、メモリの割り当てと割り当て解除を処理する可能性がある、私がキャッチしていないエラーがまだいくつかあります。助けてください!

 //alternate constructor that allows for setting of the inital value of the string
 MyString::MyString(const char *message)
 {
    int counter(0);
    while(message[counter] != '\0')
    {
            counter++;
    }
    Size = counter;
    **String = new char [Size];**
    for(int i=0; i < Size; i++)
            String[i] = message[i];

 }


istream& operator>>(istream& input, MyString& rhs)
{
    char* t;
    int size(256);
    t = new char[size];
    input.getline(t,size);

    **rhs = MyString(t);**
    delete [] t;

    return input;
}



 /*Assignment operator (=) which will copy the source string into the destination string. Note that size of the destination needs to be adjusted to be the same as the source.
 */

  MyString& MyString::operator=(const MyString& rhs)
 {
    if(this != &rhs)
    {
            delete [] String;
            **String = new char[rhs.Size+1];**
            Size = rhs.Size;

            for(int i = 0; i < Size; i++)
            {
                   ** String[i] = rhs.String[i];**
            }
    }

    return *this;
 }

助言がありますか??(すべての問題行には**があります)

4

1 に答える 1

0

私が見ていることの1つは、コピーコンストラクターがスペースを割り当てて\0おらず、コピーしていないことです。代入演算子もそうではありません..または、終端ゼロを保存していない場合、なぜそれを探しているのでしょうか?

2 つの実装は異なりますが、なぜ矛盾 (サイズとカウンター) があるのでしょうか?

「私が言えることは、問題なく動作する」-未定義の動作と呼ばれます。この場合は幸運です-または、私が好きでバグを捕まえるのが好きな場合は、不幸です.

于 2012-07-17T15:24:47.303 に答える