简体   繁体   English

重新增长数组时出错:写入时缓冲区溢出

[英]Error while regrowing an array: Buffer overrun while writing to

So I was trying to regrow this 1D dynamic array and I am unable to fix this error: Buffer overrun while writing to 'new_arr': the writable size is 'newLength*1' bytes, but 2 bytes might be written所以我试图重新增长这个一维动态数组,但我无法修复这个错误:写入“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;
}

A buffer overrun error generally detects if you try to write in a not allocated space that is probably due to a newLength smaller than the length itself that can be avoided with an if-return check:缓冲区溢出错误通常检测您是否尝试写入未分配的空间,这可能是由于newLength小于可以通过 if-return 检查避免的length本身:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:写入数组时缓冲区溢出。 如何计算以某个字母开头的单词 - Error: buffer overrun while writing to array. How to cout the word which starts with certain letter 写入“array”时缓冲区溢出:可写大小为“1*4”字节,但可能写入“8”字节 - Buffer overrun while writing to 'array': the writable size is '1*4' bytes, but '8' bytes might be written 错误:C6386:写入“newArr”时缓冲区溢出:可写大小为“int current_size*1”字节,但可能写入“2”字节 - Error: C6386: Buffer overrun while writing to 'newArr': the writable size is 'int current_size*1' bytes, but '2' bytes might be written VS2015:[C6386] 写入时缓冲区溢出(即使对于相同的索引值) - VS2015: [C6386] Buffer Overrun while writing (even for same index value) 读取文件时字符缓冲区被溢出 - Character buffer being overrun while reading file 为什么我在写入“ptr”时收到“C6386”缓冲区溢出警告? - Why am I getting warning 'C6386' Buffer overrun while writing to 'ptr'? VS2019:[C6386] 缓冲区溢出而到 - VS2019: [C6386] Buffer Overrun while to 从二维指针和重新生成文件中的字符输入时发生异常错误 - Exception Error while char input from file in 2D Pointers and Regrowing 数组的重排元素:基于堆栈的缓冲区溢出错误 - Shuffling elements of Array : stack-based buffer overrun error 缓冲区溢出? - Buffer is overrun?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM