Thursday 15 September 2011

c - free memory allotted to 3D matrix -


I assign memory for 3D matrix from the following code.

  Double *** AllocMatrix3 (Short NRH, Small NCH, Small NF) {Short Eye, J, K; Double *** meter; M = (double ***) Molkok (NRH * size (double ***)); For (i = 0; i & lt; = nrh; i ++) {m [i] = (double **) molk (nc * size * (double *)); For (J = 0; J & lt; = nk; j ++) {m [i] [j] = (double *) maulok (nf * size (double)); } For (j = 0; j & lt; = nch; j ++) for m [i] [j] [k] (k = 0; k & lt; = nph; k ++) ] For = (i = 0; i & lt; = nrh; i ++) = 0.0; Refund M; }   

But when I try to empty the memory by using the code given below, it does not work

  Free from zero to freematics 3 (Double *** M, Short NRL, Small NRH, Small NCL, Small NCH, Small NPL, Small NF) {Small Eye, J, K; For (i = nrh; i & gt; = 0; i--) (j = nch; j & gt; = 0; j--) free ((m [i] [j])); Free (M [i]); }   

Can you please help Thanks in advance? Instead of using malloc and instead of setting values ​​to

You can use calloc for final allocation (at the double level).

line m = (double ***) malloc (nrh * sizeof (double ***)); nrh will allocate rooms to elements, but later you repeat with (i = 0; i Which sends it to NRH + 1 again and again. You need to change the call to malloc or .

For free , you have to:

  • free m [i] [j] ] for all i and j
  • for free
  • free m

    Basically, you should always add an incentive to your statement that helps prevent such issues.

    In addition, do you really need jagged arrays and need to return double *** ? You may be able to do the same thing by returning the calloc (nrh * nch * nph, sizeof (double)) , after which you can get a code free from free can do.

    Warning, the share of calloc can not always be applied to floating point values. It should always be applicable to integral types.

No comments:

Post a Comment