c++ - 删除字符指针得到堆错误

标签 c++ oop delete-operator chaining

下面的代码应该实现我自己的字符串类。类似于您要创建类似这样的内容 String s = "Hi";。当它销毁并到达 delete[] data 的部分时,我收到一个错误。是说我在堆缓冲区外时正在写。这些不是 cstring,因此我的字符串末尾没有空字符。

这是我的转换/默认构造函数:

    String346::String346(const char * oldString) : data(NULL), size(static_cast<unsigned int>(strlen(oldString))){
    data = new(std::nothrow) char[size];
    for (unsigned int i = 0; i <= getSize(); i++){
        data[i] = oldString[i];
    }
}

由于这些函数需要支持函数链,我将把与我的问题相关的两个函数放在一个中,如果传递了一个 String346 对象,或者如果传递了一个 char * 被传入了。

传入 char * 的连接函数:

String346 & String346::concat(const char * catString) {
    String346 newCatString(catString);
    concat(newCatString);
    return (*this);
}

传入 String346 对象的连接函数:

String346 & String346::concat(const String346 & catString) {
        String346 tempData(data);
        size = tempData.getSize() + catString.getSize();
        destroy();
        data = new (std::nothrow) char[size];
        if (data == NULL){
            std::cout << "Not enough space to concatinate this string." << std::endl;
        }
        else{
            unsigned int index = 0;
            for (unsigned int i = 0; i < getSize(); i++){
                if (i < tempData.getSize()){
                    data[i] = tempData.data[i];
                }
                else{
                    data[i] = catString.data[index];
                    index++;
                }
            }       
        }
        return (*this);
    }

我的 destroy 函数完成了对象销毁的所有工作,它很简单。它包含以下三行:

    delete[] data;
    data = NULL;
    size = 0;
    return;

最佳答案

您的构造函数分配一个包含 size 元素的 char 数组。

然后,您的构造函数似乎将 size+1 字符复制到数组(我假设 getSize() 返回 size)。

因此,构造函数代码运行到数组末尾,并破坏了分配数组末尾后的一个字节。

附言static_cast 不是必需的,只会使代码更加混淆。

关于c++ - 删除字符指针得到堆错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36254461/

相关文章:

c++ - 何时对使用 'delete' 创建的临时对象调用 `new` ?

c++ - SFINAE 上的默认参数值

C++ qsort 二维数组

opencv - libopencv_calib3d : undefined reference to `std::__throw_out_of_range_fmt(char const*, …)@GLIBCXX_3.4.20'

ios - UITableView 的属性可以是 UITableView Delegate 和 DataSource

c++ - 为什么我必须在 "original"指针上调用 delete?

c++ - 在 Windows 7 上崩溃但在 XP 上运行

c++ - 在 C++ 中使用函数作为类成员

javascript - 在 ES6、OOP Javascript 编程中转换 ES5 IIFE

C++删除动态数组的最后一个元素