【问题标题】:Invalid read and write of size in valgrindvalgrind中大小的读取和写入无效
【发布时间】:2012-07-17 15:02:39
【问题描述】:

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

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

【问题讨论】:

  • 我应该发布该信息,我将编辑问题,并以某种方式突出显示特定行。对不起!

标签: string oop function error-handling size


【解决方案1】:

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

而且两种实现方式不同,为什么不一致(Size vs counter)?

“据我所知,它运行良好” - 这称为未定义行为,或者在这种情况下:运气 - 或者,如果您喜欢我,并且喜欢捕捉错误:不幸。

【讨论】:

  • 非常感谢!我测试了复制构造函数以查看它是否复制了 \0 并显示它确实如此。复制的字符串应该是 Hello World,它有 10 个字符并获得 11 个索引以用于 nul 字符。我测试了使用 cout
  • 它们到底有什么不同?我以为我正在达到尺寸等于计数器的位置?我想我在编写代码时可能已经超越了自己。
  • 它不复制它,做一个适当的测试。
  • 我刚测试过:if(String[11] != '\0') { cout
  • 对不起,那是在我的复制构造函数中,你是绝对正确的 nul 没有在我的赋值运算符中复制。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
相关资源
最近更新 更多