Visual c++ MyString的复制构造函数导致堆错误。仅在调试模式下给出错误

Visual c++ MyString的复制构造函数导致堆错误。仅在调试模式下给出错误,visual-c++,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 MyStrin

所以,我以前从未经历过这种情况。通常,当我遇到错误时,它总是触发一个断点。但是,这一次,当我构建解决方案并在不进行调试的情况下运行它(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.
这项任务今晚就要交了,所以我非常感谢任何快速的帮助

我的代码在这里:

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

关键是,在我尝试重载操作符>>之前,这行代码没有问题。为了调试这段代码,我放弃了这段代码


再次感谢您的帮助

让我们看一下第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) 另外,在处理原始字节(字符)时,您不希望使用new()和delete(),而是使用malloc()和free()。在这种情况下,在诸如copy()之类的函数中,您只需使用realloc(),而不用先调用delete()然后调用new()

编辑:
还有一件事:堆损坏导致的错误通常发生在调试期间。在release binary中,这将简单地覆盖一些已释放(可能已经被其他人使用)的内存。这就是为什么在C++中使用内存进行调试非常重要。

请在您的帖子中发布相关代码,而不是在其他站点上。
copy()
{
    if(this->pData)
    {
        delete this->pData;
    }
    //now allocate new buffer and copy
}