I am filling an empty array with randomly generated numbers between 0 and 100000 but the line "array[i] = rand() % 100000;" has a green underline and says "Buffer overrun while writing to 'array': the writable size is '1*4' bytes, but '8' bytes might be written". Does anyone know how to fix this?
#include <iostream>
#include <Windows.h>
#include <time.h>
#pragma
using namespace std;
int main() {
int N;
cout << "Enter a value for N: ";
cin >> N;
int* array = new int(N);
srand(time(0));
for (int i = 0; i < N; i++) {
array[i] = rand() % 100000;
}
for (int i = 0; i < N; i++) {
cout << array[i] << ", ";
}
delete array;
return 0;
}
new int(N);
creates a single int
with the initial value N
.
For an array, write new int[N];
To free this memory you need to write delete[] array;
: the behaviour of delete array;
will be undefined.
Note that a drop-in replacement that takes care of all the memory management for you would be
std::vector<int> array(N);
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.