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



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

这是我现在的代码。

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

最新更新