Malloc problems

Stephen Spencer spencer at kazoo.cis.ohio-state.edu
Mon May 16 22:32:31 AEST 1988


In article <690008 at hpfelg.HP.COM> jk at hpfelg.HP.COM (John Kessenich) writes:
>
>A wild guess:
>    Malloc() has two behavoirs that combined might be causing your
>    problem.
>        1.  When malloc() runs out of memory, it returns NULL.
>        2.  Free does not necessarily return memory for malloc's
>		immediate re-use.
>    If you repeatedly malloc and free, you may actually be using 
>    up memory.  This leads to malloc eventually returning NULL,
>    which, if you dereference, can cause a core dump.
>    Free-ing memory in reverse order it was malloc'ed in may help.
>John Kessenich

It is true that when malloc() runs out of memory, the call to malloc()
will return NULL.  I would sincerely hope that one's code would be
robust enough to look SOMETHING like this:

     short *pi;

     pi = (short *)malloc(sizeof(short));
     if (pi == NULL) 
     {
	fprintf(stderr,"HELP!!!! Cannot allocate memory for pi.\n");
     }

Good (in my estimation) code would test any and all dynamically allocated
memory for successful completion of the malloc() call.  

I suppose that 'garbage collection' would be too machine-dependent.
It'd sure be a nice feature.



-=-
Stephen Spencer, Graduate Student       |
The Computer Graphics Research Group    | spencer at tut.cis.ohio-state.edu
The Ohio State University (614)292-3416 | 
1224 Kinnear Road, Columbus OH 43212    | ICBM: 39'58" N, 83'03" W



More information about the Comp.lang.c mailing list