【问题标题】:Error while regrowing an array: Buffer overrun while writing to重新增长数组时出错:写入时缓冲区溢出
【发布时间】:2020-10-04 21:05:13
【问题描述】:

所以我试图重新增长这个一维动态数组,但我无法修复这个错误: 写入“new_arr”时缓冲区溢出:可写入大小为“newLength*1”字节,但可能写入 2 个字节

void regrow(char *&arr, int &length,int newLength) //Funcion to regrow an array
{
    char* new_arr = new char[newLength];
    for (int index = 0; index < length; index++)
    {
        new_arr[index] = arr[index];   //**Error occurs here** 
    }
    length = newLength;
    delete[] arr;
    arr = new_arr;
}

【问题讨论】:

  • std::vector 类已经为您完成了这项工作。
  • length和newLength的值是多少?
  • 看起来newLength 小于length。
  • 是的,现在问题已经解决了。顺便说一句,我不允许为此使用向量。不过还是谢谢大家。

标签: c++ arrays memory dynamic memory-leaks


【解决方案1】:

缓冲区溢出错误通常会检测您是否尝试写入未分配的 空间可能是由于 newLength 小于 length 本身 这可以通过 if-return 检查来避免:

#include <iostream>

void regrow(char *&arr, int &length,int newLength) //Funcion to regrow an array
{
    if(length >= newLength){ //Check for correct input
        return;
    }else{

    char* new_arr = new char[newLength];
    for (int index = 0; index < length; index++)
    {
        new_arr[index] = arr[index];   //**Error occurs here**
    }
    length = newLength;
    delete[] arr;
    arr = new_arr;
    }
}

int main()
{
    int a = 5;
    int b = 8;
    char*array = new char[a]{'C','B','a','d','f'};

    regrow(array,a,b);


    for(int i = 0; i < a; ++i){
        std::cout << array[i] << std::endl;
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2010-11-11
    • 2012-03-03
    相关资源
    最近更新 更多