简体   繁体   中英

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM