删除字符串时堆损坏 [英] Heap corruption when deleting a string
问题描述
这是我的代码:
std::string readString()
{
int strLen = Read<int>();
char* rawString = new char[strLen];
Read(rawString, strLen);
rawString[strLen] = '\0';
std::string retVal(rawString);
delete [] rawString;
return retVal;
}
第一行读取字符串的长度。
第二行创建一个新的字符数组(c-字符串),字符串长度为
第三行读取字符串(从文件读取它)
第四行添加一个NULL到结束。
第5行从c字符串中创建一个std :: string。
第6行删除c字符串(HEAP CORRUPTION HAPPENS HERE)
第7行返回字符串,但由于错误,它不会到达这一点。
The first line reads the length of the string.
The second line creates a new char array (c-string) with the string length
The third line reads the string (its reading it from a file)
The 4th line adds a NULL to the end.
The 5th line creates an std::string out of the c-string.
The 6th line deletes the c-string (HEAP CORRUPTION HAPPENS HERE)
The 7th line returns the string, but it never reaches this point because of an error.
在第6行,我得到一个堆损坏错误:
CRT检测到应用程序在堆缓冲区结束后写入内存。
On the 6th line I get a heap corruption error: CRT detected that the application wrote to memory after end of heap buffer.
我的问题可能很明显,但为什么我得到一个堆损坏?当我创建一个std :: string,它应该复制该字符串,我应该安全删除c字符串。
My question may be obvious, but why am I getting a heap corruption? When I create an std::string, it should copy the string, and I should be safe to delete the c-string.
目前,我怀疑std :: string在我删除它后试图访问c字符串。
Currently, I'm suspecting that std::string is trying to access the c-string after I delete it.
有什么想法吗?
推荐答案
更改:
char* rawString = new char[strLen];
到:
char* rawString = new char[strLen + 1];
这篇关于删除字符串时堆损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!