复制MyString的构造函数会导致HEAP错误。仅在调试模式下出现错误

时间:2013-09-24 17:57:18

标签: visual-c++

所以,我以前从未经历过这个。通常当我收到错误时,它总是触发一个断点。但是,这次我构建解决方案并在没有调试的情况下运行它(ctrl + F5),它没有给我任何错误并正确运行。但是当我尝试调试它(F5)时,它给了我这个错误:

HEAP[MyString.exe]: HEAP: Free Heap block 294bd8 modified at 294c00 after it was freed
Windows has triggered a breakpoint in MyString.exe.

This may be due to a corruption of the heap, which indicates a bug in MyString.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while MyString.exe has focus.

The output window may have more diagnostic information.

这项任务将于今晚到期,所以我很感激您的帮助。

我的代码在这里: https://gist.github.com/anonymous/8d84b21be6d1f4bc18bf

我已经将问题缩小到main.cpp中第18行的主要内容(c = a + b;)连接成功,但是当它被复制到c时,错误消息发生在第56行在MyString.cpp中(pData = new char [length + 1];)。

在我尝试重载运算符>>之前,我对这行代码没有任何问题。为了试图调试它,我已经废弃了这段代码。

再次,任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

让我们看看第18行:

1. In line 17 you create string c with dynamically allocated memory inside.
2. You make assignment: c = a + b:
  2.1. Operator+ creates LOCAL object 'cat'.
  2.2. cat's memory is allocated dynamically.
  2.3. cat becomes concatenation of two given strings.
  2.4. Operator+ exits. cat is LOCAL object and it's being destroyed.
    2.4.1. cat is being destroyed. cat's destructor runs.
    2.4.2. destructor deletes pData;
    2.4.3. After delete you make *pData = NULL. //ERROR - should be pData = NULL (1)
  2.5. c is initialized with result of operator+.
  2.6. operator= calls copy().
  2.7. copy() allocates new memory without checking the current one. //ERROR - memory leak (2)

<强>(1) pData是char *。在析构函数中,我们有:delete [] pData(删除内存),然后* pData = NULL。 因为pData是指针,所以* pData与pData [0]相同。所以你写了已经释放的内存。这是导致错误的原因。

<强>(2) 其他问题。 Copy()会覆盖当前内存而不进行检查。应该是:

copy()
{
    if(this->pData)
    {
        delete this->pData;
    }
    //now allocate new buffer and copy
}

此外,在处理原始字节(字符)时,您不希望使用new()和delete(),而是使用malloc()和free()。在这种情况下,在copy()之类的函数中,您只需使用realloc()而不是调用delete()然后调用new()。

编辑: 还有一件事:堆损坏引起的错误通常发生在调试过程中。在发布二进制文件中,这将简单地覆盖一些释放(并且可能已被其他人使用)内存。这就是为什么在C ++中使用内存时调试非常重要。