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

问题描述

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

这是我的代码

//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] = '\0';
                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;

        }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...