使用析构函数删除指针时,C++ Block Type is Valid 错误

标签 c++

<分区>

#include <iostream>
#include <string>
using namespace std;

class String
{
private:
    int len;
    char *str;

public:
    String() {}

    String(const char *string):len(strlen(string))
    {
        str = new char[len + 1];
        strcpy(str, string);
    }

    String& operator=(const String& st)
    {
        len = st.len;
        str = new char[len];
        strcpy(str, st.str);
        return *this;
    }

    String operator+(const String& obj)
    {
        char *temp = new char[len + obj.len + 1];
        strcpy(temp, str);
        strcat(temp, obj.str);
        String copy(temp);
        delete[]temp;
        return copy;
    }

    ~String()
    {
        delete[] str;
    }
};

void main()
{
    String str1 = "Hel";
    String str2 = "low";
    String str3 = str1 + str2;
}

我正在尝试使用析构函数删除 String 类中的指针。

但是我看到了 Block Type Is Valid 的消息。

你能告诉我为什么吗?

而且,我很抱歉对齐不正确,这是我第一次在 stackoverflow 中提问

最佳答案

我发现您的代码中至少有一个错误会导致未定义的行为。我不熟悉你问的实际编译器诊断,但未定义的行为是未定义的行为。谁知道。

错误是赋值运算符分配的缓冲区太短。结果,这段代码将踩在堆上。

赋值运算符应该做的:

str = new char[len+1];

您的构造函数将 len 设置为不包括终止空字节的字符串的大小。随后,赋值运算符将为分配的字符串分配少一个字节。比较构造函数中的 new 和赋值运算符中的 new

赋值运算符也会通过不释放现有缓冲区来泄漏内存,但这是一个单独的问题。

关于使用析构函数删除指针时,C++ Block Type is Valid 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33028760/

相关文章:

c++ - Objective-C++ 将 std::string 转换为 NSString

c++ - 如何将结构数组传递给C++

c++ - 为什么 C++ 编译器在这个简单的程序中不给予优先权(赋值下的递增运算符)?

c++ - 我不能将 NULL 作为构造函数的参数发送吗?

c++ - 如果 C++ 枚举的 switch 语句中的枚举值 > const N,如何获取?

c++ - QString::startWith() 和 QStringList::removeAll() 未按预期运行

c++ - 有没有办法根据用户对配对 vector 进行排序?

c++ - 在 Linux-64 上编译 NeHe(或其他面向 32 位的)示例

c++ - 我可以在 C++ 中通过 > < 比较字符串吗

c++ - OpenGL 使用着色器定义颜色