c++visual-c++bufferbuffer-overrun

Buffer-overrun, Don't know why this warning is occuring?


Wrote a program to create a dynamic array and append a new value taken from the user into the new array 'arr2', While also copying the elements from the previous array 'arr1' into the new dynamic array 'arr2'. The program runs and executes but the following warning shows up "Warning C6386 Buffer overrun while writing to 'arr2': the writable size is 'size*4' bytes, but '8' bytes might be written". This is the code:

#include <iostream>
using namespace std;

void add(int array[], int size, int value);

void main()
{
    int s = 5, v={}, arr1[5] = {1,2,3,4,5};
    
    cout << "\nHere is an array: ";
    for (int i = 0;i < 5;i++)
    {
        cout << arr1[i] << " ";
    }
    
    cout << "\nValue you want to add: ";
    cin >> v;
    add(arr1, s,v);

}
void add(int array[], int size, int value)
{
    size = size + 1;
    int* arr2 = new int[size];

    for (int i = 0;i < 5;i++)
    {
        arr2[i] = array[i];//Warning Occurs here at line 28

    }

    arr2[size - 1] = value;

    cout << "Here is the array with the added value: ";

    for (int i = 0;i < size;i++)
    {
        cout << arr2[i] << " ";
    }

    delete[] arr2;
}

Here is the build-log:

Build started...
1>------ Build started: Project: Practiceformid, Configuration: Debug x64 ------
1>task2.cpp
1>C:\Users\ymaso\source\repos\Practiceformid\Practiceformid\task2.cpp(7,1): warning C4326: return type of 'main' should be 'int' instead of 'void'
1>Practiceformid.vcxproj -> C:\Users\ymaso\source\repos\Practiceformid\x64\Debug\Practiceformid.exe
1>Done building project "Practiceformid.vcxproj".
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

I kind off have a hint why this is occuring maybe because the previous array that is being copied into the new array is small and it leaves an empty index in the new array that will return a null or garbage value. But I do later on fill it with the new value.


Solution

  • Your function may be called with any value for "size". If size would be for example 1, then the new size of the new array would be 2.

    Then you run your loop 5 times and access out of bound values.

    Additionally your size my overflow (wrap around) by adding 1.

    For your program, where you call your function with a fixed size array of 5, nothing will happen. For other values, there may be a problem.

    The loop should run until "size-1".

    for (int i = 0; i < size-1; i++).

    As a side note:

    In general, you should avoid signed integer data types for sizes of arrays. please use size_t instead.