sorry_I_wont sorry_I_wont - 1 year ago 68
C++ Question

Program crashes when assigning value to too many dynamically allocated arrays - C++

I have around +30 dynamically allocated arrays in my program that area each defined like following:

int Nx = 240;
int Ny = 240;
double* array = new double(Nx*Ny);

I can assign values to 16 of them, but once I reach the 17th, it throws seg fault!

This is the code that throws it, which is totally fine!

for (int i = 0; i < Nx*Ny; i++) {
array[i] = 0;

I really have no idea why, I thought of running out of heap, but since I have 4GB of RAM that should be impossible!
I am using MSVS15 and running the program on Windows 10!

Any idea why this happens?
Exact error:

Exception thrown at 0x00298389 in ecostress.exe: 0xC0000005: Access violation writing location 0x01D2B000.
If there is a handler for this exception, the program may be safely continued.

Answer Source

Simple typo:

double* array = new double(Nx*Ny); // creates a single, initialized double
double* array = new double[Nx*Ny]; // creates an array of doubles
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download