导致堆损坏的字符串擦除函数

String erase function causing heap corruption

您好,我正在处理我的字符串 class,我想添加一个擦除功能。所以我想我会采用复制起始索引之前的内存的策略,然后复制长度+起始索引之后的内存。这只会复制要删除的部分之外的数据。

这是我现在的代码。

//size is the current size of the string not including the null terminator character
//data is the character array of data

    void erase(const size_t start, const size_t length) {
            if (start + length <= size) {
                size_t tempsize = start + length;
                char* temp = new char[size + 1 - length];
                
                //copy before start
                if(start > 0)
                    memcpy(temp, data, start);

                //copy after start (including null terminator character)
                memcpy(temp + start, data + start + length, size + 1 - length - start);

                delete[] data;

                data = temp;
                data[size] = '[=10=]';
                size = tempsize;
            }
    }

通过删除所需的字符数量,它完全可以正常工作,但是当我删除字符串时它会抛出堆损坏错误。

我不知道为什么但它停止抛出异常,如果你需要的话,这里是当前代码。

void erase(const size_t& start, size_t length) {
            if (start >= size) {
                return;
            }

            if (start + length > size) {
                length = size - start;
            }

            char* temp = new char[size + 1 - length];

            //copy before start
            if (start > 0)
                memcpy(temp, data, start);

            //copy after start (including null terminator character)
            memcpy(temp + start, data + start + length, size + 1 - length - start);

            delete[] data;

            data = temp;
            size = size - length;

        }