在valgrind中读取和写入大小无效

时间:2012-07-17 15:02:40

标签: string oop function error-handling size

使用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;
 }

有什么建议吗? (所有问题行都有**)

1 个答案:

答案 0 :(得分:0)

我看到的一件事是你的复制构造函数不为\0分配空间而不复制它。也没有赋值运算符..或者,如果你不存储终止零,那你为什么要找它呢?

并且两个实现不同,为什么不一致(Size vs counter)?

“我可以告诉它运行正常” - 它被称为未定义的行为,或者在这种情况下:运气 - 或者,如果你喜欢我,并且喜欢捕捉错误:不幸。