Yasien - 11 months ago 58

C++ Question

I tried to allocate memory for structure members:

this is the structure:

`struct conserved_variables {`

double **roh;

double **mx;

double **my;

double **E;

};

I constructed an array of this structure

`conserved_variables ** U= new conserved_variables*[Ny];`

for (int i = 0; i < Ny; i++)

{

U[i] = new conserved_variables[Nx];

}

Then I tried to allocate arrays for each member in this structure:

`for (int i = 0; i < Ny; i++)`

for (int j = 0; j < Nx; j++)

{

U[i][j].E = new double*[Order + 1];

U[i][j].mx = new double*[Order + 1];

U[i][j].my = new double*[Order + 1];

U[i][j].roh = new double*[Order + 1];

for (int k = 0; k <= Order; i++)

{

U[i][j].roh[k] = new double[Order + 1];

U[i][j].mx[k] = new double[Order + 1];

U[i][j].my[k] = new double[Order + 1];

U[i][j].E[k] = new double[Order + 1];

}

}

I got this error message:

`Exception thrown at 0x01153FDD in FR_1D_Advection_Equation.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD.`

If there is a handler for this exception, the program may be safely continued.

Answer Source

This is a memory locality nightmare.

As for your actual bug, you were not careful with your inner loop:

```
for (int k = 0; k <= Order; i++)
// ^
// you mean k
```

This is exploding because you accidentally push `i`

way past the bounds of the `U`

array. It should have been easy to spot if you had spent as much time using a debugger as it took you to ask the question on Stack Overflow.