2

我已经尝试解决这个问题好几个小时了,但我已经束手无策了。如果有人能在我做错时告诉我,我一定会很感激。

我编写了一个简单的类来模拟字符串的基本功能。该类的成员包括一个字符指针数据(它指向一个动态创建的字符数组)和一个整数strSize(它保存字符串的长度,没有终止符。)

由于我使用的是newdelete,因此我已经实现了复制构造函数和析构函数。当我尝试实现operator+=时,会出现我的问题。LHS 对象正确构建了新字符串——我什至可以使用 cout 打印它——但是当我尝试在析构函数中释放数据指针时出现问题:我在指向的内存地址处得到“在正常块后检测到堆损坏”通过数据数组析构函数试图解除分配。

这是我完整的课程和测试程序:

#include <iostream>

using namespace std;

// Class to emulate string
class Str {
public:

    // Default constructor
    Str(): data(0), strSize(0) { }

    // Constructor from string literal
    Str(const char* cp) {
        data = new char[strlen(cp) + 1];
        char *p = data;
        const char* q = cp;
        while (*q)
            *p++ = *q++;
        *p = '\0';
        strSize = strlen(cp);
    }

    Str& operator+=(const Str& rhs) {
        // create new dynamic memory to hold concatenated string
        char* str = new char[strSize + rhs.strSize + 1];

        char* p = str;                  // new data
        char* i = data;                 // old data
        const char* q = rhs.data;       // data to append

        // append old string to new string in new dynamic memory
        while (*p++ = *i++) ;
        p--;
        while (*p++ = *q++) ;
        *p = '\0';

        // assign new values to data and strSize
        delete[] data;
        data = str;
        strSize += rhs.strSize;
        return *this;
    }


    // Copy constructor
    Str(const Str& s)
    {
        data = new char[s.strSize + 1];
        char *p = data;
        char *q = s.data;
        while (*q)
            *p++ = *q++;
        *p = '\0';
        strSize = s.strSize;
    }

    // destructor
    ~Str() { delete[] data;  }

    const char& operator[](int i) const { return data[i]; }
    int size() const { return strSize; }

private:
    char *data;
    int strSize;
};

ostream& operator<<(ostream& os, const Str& s)
{
    for (int i = 0; i != s.size(); ++i)
        os << s[i];
    return os;
}


// Test constructor, copy constructor, and += operator
int main()
{
    Str s = "hello";        // destructor  for s works ok
    Str x = s;              // destructor for x works ok
    s += "world!";          // destructor for s gives error
    cout << s << endl;
    cout << x << endl;
    return 0;
}

编辑:加速 C++ 问题 12-1。

4

4 回答 4

4

以下代码块使 p 指向数组旁边。

while (*p++ = *q++) ;
*p = '\0';

您在复制构造函数中使用的更好(和安全)的解决方案:

while (*q)
    *p++ = *q++;
*p = '\0';
于 2010-05-02T18:03:53.397 回答
3

这里已经有很多很好的答案,但值得将Valgrind作为解决此类问题的工具。如果您可以使用 *nix 框,Valgrind 工具可以成为真正的救星。

只是为了向您展示,这是我在通过它编译和运行程序时得到的:

% g++ -g -o 测试 test.cpp
% valgrind ./测试
==2293== Memcheck,内存错误检测器
==2293== 版权所有 (C) 2002-2009 和 GNU GPL,由 Julian Seward 等人提供。
==2293== 使用 Valgrind-3.5.0-Debian 和 LibVEX;使用 -h 重新运行以获取版权信息
==2293== 命令:./test
==2293==
==2293== 大小为 1 的无效写入
==2293== 在 0x8048A9A: Str::operator+=(Str const&) (test.cpp:36)
==2293== by 0x8048882: main (test.cpp:82)
==2293== 地址 0x42bc0dc 在大小为 12 的块分配后为 0 字节
==2293== at 0x4025024: operator new[](unsigned int) (vg_replace_malloc.c:258)
==2293== by 0x8048A35: Str::operator+=(Str const&) (test.cpp:26)
==2293== by 0x8048882: main (test.cpp:82)
==2293==
你好世界!
你好
==2293==
==2293== 堆摘要:
==2293== 在退出时使用:0 个块中的 0 个字节
==2293== 总堆使用量:4 个分配,4 个释放,31 个字节分配
==2293==
==2293== 所有堆块都被释放——不可能有泄漏
==2293==
==2293== 对于检测到和抑制的错误计数,重新运行:-v
==2293== 错误摘要:来自 1 个上下文的 1 个错误(抑制:来自 6 个的 17 个)
%

您可以看到它指出了此处其他答案指出的行(第 36 行附近)。

于 2010-05-03T06:50:21.637 回答
2
while (*p++ = *i++) ; // the last iteration is when i is one past the end
// i is two past the end here -- you checked for a 0, found it, then incremented past it
p--; //here you corrected for this
while (*p++ = *q++) ;// the last iteration is when p and q are one past the end
// p and q are two past the end here
// but you didn't insert a correction here
*p = '\0';  // this write is in unallocated memory

使用类似于您在复制构造函数中使用的习语:

while (*i) *p++ = *i++; //in these loops, you only increment if *i was nonzero
while (*q) *p++ = *q++;
*p = '\0'
于 2010-05-02T18:06:29.143 回答
1

您已经有两个答案指向导致您丢弃堆的特定错误。假设这是家庭作业或其他形式的练习(否则我们都会因为你编写自己的字符串类而对你大喊大叫),这里还有一些事情要为你咀嚼:

  • 如果您觉得需要注释代码,请考虑使其更具表现力
    例如,代替char* p = str; // new data,您可以只写char* new_data = str;
    代替//do frgl, 后跟一段代码,你可以写do_frgl();. 如果函数是内联的,它对生成的代码没有影响,但对代码的读者有很大的不同。
  • 包括您的标头在内的每个人都将所有内容从命名空间std转储到全局命名空间中。这根本不是一个好主意。我会避免像瘟疫一样包括你的标题。
  • 你的构造函数应该在初始化列表中初始化他们的类成员。
  • 您的构造函数为同一个字符串Str::Str(const char*)调用了两次。应用程序代码应该尽可能快,另一方面,如果您不知道它在哪个应用程序中结束,库代码应该尽可能快。您正在编写库代码。std::strlen()
  • size()成员函数可以返回负值吗?如果不是,为什么它是有符号整数?
  • 这段代码会发生什么:Str s1, s2; s1=s2
  • 那么这个呢:Str str("abc"); std::cout<<str[1];

(如果遇到此问题的人可以想到更多提示,请随时扩展此内容。)

于 2010-05-02T18:44:42.347 回答