3

For the program I am writing I need to create an array with a user-defined size, as well as random values between -15 and 15. As such i am using srand along with dynamic array casting. This is my full code below:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    //initialize variables
    double minValue;
    double maxValue;
    double firstQuartile;
    double thirdQuartile;
    double skewness;

    int size;
    std::cout << "Please enter the size of the data set: ";                 //get data set size from user
    std::cin >> size;
    int* dataSet = new int[size];                                                           
    cout << endl << "These are the randomly generated values: ";

    srand(static_cast<unsigned int>(time(NULL)));

    int i = size;
    for (int x = 0; x < i; x++)                                         //generate random numbers
    {
        dataSet[i] = (rand() % 31) - 15;
        cout << dataSet[i] << " ";
    }


} 

While it still compiles, I need it to do so without errors and the section I've highlighted below is causing two errors I do not know how to fix.

int i = size;
    for (int x = 0; x < i; x++)                                         //generate random numbers
    {
        dataSet[i] = (rand() % 31) - 15;
        cout << dataSet[i] << " ";
    }

C6386 Buffer overrun while writing to 'dataSet': the writable size is 'size*4' bytes, but 'i' bytes might be written.

AND

C6385 Reading invalid data from 'dataSet': the readable size is 'size*4' bytes, but 'i' bytes may be read.

J. Kent
  • 35
  • 1
  • 6

1 Answers1

7

In this loop the index variable x not i.

So change the loop like

int i = size;
for (int x = 0; x < i; x++)                                         //generate random numbers
{
    dataSet[x] = (rand() % 31) - 15;
    cout << dataSet[x] << " ";
}

In fact the variable i is redundant and makes the code error prone. Why not to write

for (int i = 0; i < size; i++)                                         //generate random numbers
{
    dataSet[i] = (rand() % 31) - 15;
    cout << dataSet[i] << " ";
}
user4581301
  • 33,082
  • 7
  • 33
  • 54
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thanks for the quick response. I do have a follow-up question though. I still need to access the data within the array that I created so should I delete it at the end of the program? – J. Kent Feb 13 '20 at 23:41
  • 1
    @J.Kent What was allocated with the operator new should be freed with the operator delete. In your case you have to use the operator delete []. – Vlad from Moscow Feb 13 '20 at 23:43