c++ - 简单的 char* 内存分配不起作用

标签 c++ oop memory-management heap-memory

我有最简单的课文:

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/

相关文章:

python - 是否可以在不实例化类的情况下导入类方法?

ios - 应用程序运行时不断增加内存使用量(Swift)

c - 我如何知道我的 mmaped 分配的范围?

c++ - 结构体存在于函数/方法中

c++ - 为什么此类对象声明有效?

c++ - 为什么在 C++ 中如此频繁地使用 get/set 函数?

Java-经过多次迭代后,为什么字符串变量不能保存完整的文件名?

c++ - mpl序列和递归代码生成

原子的 C++ 内存屏障

c++ - "Writefile"for RS232 communication using MFC hangs forever, but