freeing dynamic memory in the r.le programs

Darrell McCauley mccauley at ecn.purdue.edu
Sun Jul 18 19:39:24 EDT 1993


BAKERWL (BAKERWL at corral.uwyo.edu) writes on 18 Jul 93:
>I have used the following code to allocate and free memory in one of the
>r.le programs:
>	pt = (int *)G_calloc(100, sizeof(int));

>	for (i=0; i<100; i++)
>	   free(pt[i]);
>	free(pt);
>
>is "int   *pt;" before the above code.  This problem was found by Lars

My understanding of C is that you only need one call to
free for every malloc call.  Therefore,
        free(pt);
should be sufficient.

When higher dimension arrays are used, then you have to
call free more than once. For example, for an NxN array:

  int **pt;
  
  if ( (pt = (int **) malloc(N*sizeof(int *))) == NULL)
    fprintf(stderr,"opps\n"), exit(-1);
  for (i=0;i<N;++i)
    if ( (pt[i] = (int *) malloc(N*sizeof(int))) == NULL)
      fprintf(stderr,"opps\n"), exit(-1);

  ...

  for (i=0;i<N;++i)
    free(pt[i]);
  free(pt);

see the FAQ for comp.lang.c (available via anonymous ftp
from rtfm.mit.edu:pub/usenet/comp.lang.c).

BTW, is there a nice way to run lint with the Gmakefile
setup? I currently do something like this:

CC = lint
COMPILE_FLAGS = 

--Darrell



More information about the grass-dev mailing list