dynamic memory allocation - C++ Segmentation Fault After When Trying to Write to Matrix -


i have 3d matrix allocated 1 block of memory, when try write darn thing, gives me segmentation fault. thing works fine 2 dimensions, reason, i'm having trouble third...i have no idea error in allocation. looks perfect me.

here's code:

phi = new double**[xlength]; phi[0] = new double*[xlength*ylength]; phi[0][0] = new double[xlength*ylength*tlength]; (int i=0;i<xlength;i++) {     phi[i] = phi[0] + ylength*i;     (int j=0;j<ylength;j++)     {         phi[i][j] = phi[i][0] + tlength*j;     } } 

any appreciated. (yes, want 3d matrix)

also, segmentation fault if matters:

for (int = 0; < xlength; i++)     {         (int j = 0; j < ylength; j++)         {             phi[i][j][1] = 0.1*(4.0*i*h-i*i*h*h)             *(2.0*j*h-j*j*h*h);         }     } 

this work 2 dimensions though!

phi = new double*[xlength]; phi[0] = new double[xlength*ylength]; (int i=0;i<xlength;i++) {     phi[i] = phi[0] + ylength*i; } 

you did not allocate other submatrixes e.g. phi[1] or phi[0][1]

you need @ least

phi = new double**[xlength]; (int i=0; i<xlength; i++) {      phi[i] = new double* [ylength];     (int j=0; j<ylength; j++) {         phi[i][j] = new double [zlength];        (k=0; k<zlength; k++) phi[i][j][k] = 0.0;     } } 

and should consider using std::vector (or even, if in c++2011, std::array), i.e.

std::vector<std::vector<double> > phi; 

and std::vector you'll need phi.resize(xlength) , loop resize each subelement phi[i].resize(ylength) etc.


if want allocate memory @ once, have

double* phi = new double[xlength*ylength*zlength] 

but cannot use phi[i][j][k] notation, should

#define inphi(i,j,k) phi[(i)*xlength*ylength+(j)*xlength+(k)] 

and write inphi(i,j,k) instead of phi[i][j][k]


your second code not work: undefined behavior (it don't crash because lucky, crash on other systems....), memory leak don't crash yet (but crash later, perhaps re-running program again). use memory leakage detector valgrind


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -