我有最简单的课文:
class Text
{
char* txt;
public:
Text(const char*);
Text(const Text&);
~Text();
const Text operator+(const Text&) const;
};
和实现:
#include "text.h"
Text::~Text()
{
delete[] this->txt;
}
Text::Text(const char* argText)
{
txt = new char[strlen(argText)+1];
strcpy(txt, argText);
}
Text::Text(const Text& other)
{
txt = new char[strlen(other.txt)+1];
strcpy(txt, other.txt);
}
const Text Text::operator+(const Text& other) const
{
char* ttxt, *newLine;
ttxt = new char[strlen(txt)+strlen(other.txt)+2];
strcat(ttxt, this->txt);
newLine = new char[2];
newLine[0] = '\n';
newLine[1] = '\0';
strcat(ttxt, newLine);
strcat(ttxt, other.txt);
Text temp(ttxt);
delete[] newLine;
return temp;
}
和主要:
#include "text.h"
int main()
{
Text a("First text.");
Text b("Second lol!!\n kthxbye!!!!!!!");
Text c(a+b);
}
并且程序在 newLine = new char[2];
处中断 我尝试增加它,就像 new char[5] 但它仍然中断。我收到的消息是:
Windows has triggered a breakpoint in prTextClass.exe.
This may be due to a corruption of the heap, which indicates a bug in prTextClass.exe or any of the DLLs it has loaded...
最佳答案
const Text Text::operator+(const Text& other) const
{
char* ttxt, *newLine;
ttxt = new char[strlen(txt)+strlen(other.txt)+2];
strcat(ttxt, this->txt);
// ^^^^^^^^^^^^^^^^^^^^^^^^ This line is buggy
newLine = new char[2];
newLine[0] = '\n';
newLine[1] = '\0';
strcat(ttxt, newLine);
strcat(ttxt, other.txt);
Text temp(ttxt);
// ....
请注意,ttxt = new char[strlen(txt)+strlen(other.txt)+2];
不会初始化数组内容。因此,当 strcat()
被调用时,它通过 ttx
找到第一个 '\0'
字符作为字符串 ttxt
并因此停在了一个未知的位置。
你应该把它改成
strcpy(ttxt, this->txt);
关于c++ - 简单的 char* 内存分配不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11765389/