0

I am using Dr. Memory to debug legacy code that is crashing in certain conditions.

Dr. Memory says there is a memory leak during allocation:

float   ***in_vol=NULL;
in_vol=(float ***) malloc(inimsize[12]*sizeof(float **)); // here **
                   // inimsize is array of ints
 for (i0=0;i0<inimsize[12];i0++) {
   in_vol[i0] =(float **) malloc(inimsize[0]*sizeof(float *));

   for (i1=0;i1<inimsize[0];i1++)  {
      in_vol[i0][i1]=(float *) malloc(inimsize[1]*sizeof(float ));
   }
 }

The memory is later freed:

for (i0=0;i0<in_header[0][12];i0++) {
  for (i1=0;i1<in_header[0][0];i1++)  {
    free( (float*) *(*(in_vol+i0)+i1) );

  }
    free( (float*)  *(in_vol+i0));
}

free( (float*)in_vol); 
in_vol=NULL;

I do not see the problem, however, I am running out of memory during some tests.

Are the allocation and freeing correct?

Jake
  • 9
  • 1
  • it doesn't answer the question, but as you are writing C you do not need to cast the result of malloc: https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – nounoursnoir Jun 21 '17 at 23:08
  • 3
    Your allocation count is `inimsize[12]` but your free count is `in_header`. Can you post more code to show how these are set up. If it were me, I'd be using the same limits on all `for` loops – Craig Estey Jun 21 '17 at 23:10
  • You use `inimsize` when allocating and `in_header` when freeing. There's nothing to show that those sizes are the same, so a leak or memory abuse is certainly possible. – Jonathan Leffler Jun 21 '17 at 23:11
  • in_header is a copy of inimsize, so it appears to be the same. for (i=0;i<20;i++) in_header[njj][i] = inimsize[i]; } I will keep checking a provide a helpful answer when I can – Jake Jun 21 '17 at 23:19
  • Being a 3-star C programmer is not a compliment! It is always almost a signal of bad inderface design. And read [ask]. We need a [mcve]. – too honest for this site Jun 22 '17 at 00:10
  • If your diagnostic tool is telling you there's something wrong, there's likely something wrong. What the diagnostic tool can't see is the language you are using. If it could, it'd be quite verbose indeed! An array is a contiguous, *single allocation*. What you're creating is not a *3-dimensional array* but a *tree*. – autistic Dec 17 '17 at 15:19

0 Answers0