2
votes

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;
}
1
The std::vector class does this work for you already. - PaulMcKenzie
What are the values of length and newLength? - Beta
It looks like newLength is smaller than length. - molbdnilo
Yes the problem is solved now. Btw I was not allowed to use vectors for this. Thank you all though. - Hassan

1 Answers

1
votes

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