LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C: Segmentation fault when freeing allocated 2D array (https://www.linuxquestions.org/questions/programming-9/c-segmentation-fault-when-freeing-allocated-2d-array-883877/)

aihaike 06-01-2011 02:12 AM

C: Segmentation fault when freeing allocated 2D array
 
Dear all,

I know that seems to be a common question, but information from the web does not help me.
So problem is in the title.

Here is what I do:

First I declare the pointers.

Code:

double **rijx,**rijy,**rijz;
Then I allocate the require memory.

Code:

  rijx = malloc (atom_number*sizeof(double*));
  rijy = malloc (atom_number*sizeof(double*));
  rijz = malloc (atom_number*sizeof(double*));
  if ( (rijx == NULL) || (rijy == NULL) || (rijz == NULL) ){ (void)fprintf(stdout,"compute_energy_cuda_: failed to allocate rijx or rijy or rijz\n");exit (EXIT_FAILURE);}                         
  for (i=0;i<=atom_number-1;i++) {
        rijx[i] = malloc (atom_number*sizeof(double));
        rijy[i] = malloc (atom_number*sizeof(double));     
        rijz[i] = malloc (atom_number*sizeof(double));
        if ( (rijx[i] == NULL) || (rijy[i] == NULL) || (rijz[i] == NULL) ){ (void)fprintf(stdout,"compute_energy_cuda_: failed to allocate rijx[%d] or rijy[%d] or rijz[%d]\n",i,i,i);exit (EXIT_FAILURE);}
                                }

Then I initialize the arrays ....

Code:


  for (i=0;i<=atom_number-1;i++) {
    for (j=0;j<=atom_number-1;j++) {
      rijx[i][j] = 0.0;
      rijy[i][j] = 0.0;
      rijz[i][j] = 0.0;
                                  }
                                }

I do some stuff with them ...

Then I free the memory by doing

Code:

  for (i=0;i<=atom_number-1;i++) {
        (void)free(rijx[i]);
        (void)free(rijy[i]);       
        (void)free(rijz[i]);
                                }

and in crash during this step.
I do not see what's going wrong here.
Then I do this

Code:

(void)free(rijx);(void)free(rijy);(void)free(rijz);
But it does not get to here so far.

So, some hints are more than welcome.
Thanks in advance,

Éric.

dwhitney67 06-01-2011 03:41 AM

Quote:

Originally Posted by aihaike (Post 4372748)
Dear all,

I know that seems to be a common question...

Yes, it is indeed a common question, and one I just answered a couple of days ago. Please click here for an example.


P.S. I did not see anything wrong in the code you posted. Personally I am not fond of seeing if-statement condition such as i <= (N-1), preferring instead i < N .... but that is beside the point. Your code is probably crashing elsewhere.

aihaike 06-01-2011 11:12 PM

Thanks to your post, I looked for elsewhere and solve the issue.
I initialized an array with an index bigger that its size.


All times are GMT -5. The time now is 11:10 PM.