Question about malloc() and free()

Stan Brown, Oak Road Systems browns at iccgcc.decnet.ab.com
Fri Aug 31 06:46:38 AEST 1990


In article <1990Aug27.184058.1936 at everexn.uucp>, roger at everexn.uucp (Roger House) writes:
> In <118073 at linus.mitre.org> rtidd at ccels3.mitre.org (Randy Tidd) writes:
> 
>>What happens to the space that was malloc'ed? It is never freed by me;
>>will the compiler figure this out and arrange for it to be freed?  Is
>>the resolution method standard over compilers?
> 
> The compiler will NOT figure out that something can be freed and then free
> it.  Most likely the compiler has no idea that malloc is allocating memory.l
> The compiler simply compiles the code needed to pass the parameters and
> call the function.  It is up to the programmer to take care of freeing mem-
> ory allocated by the programmer.

Well, yes and no....

The idea of "allocating" memory is operating system dependent.  For
example, in MS-DOS your .EXE program has all of available memory unless it
gives some of it up.  When you execute malloc( ) it takes from this space
and puts an appropriate header on the block.  So on a DOS machine, when
your .EXE stops running, even if you malloc'd a couple of hundred K, you
should see exactly the same amount of available memory as before you ran
the program.

Multi-user systems typically work the same way.  For instance, on VAX/VMS
the system ssomehow makes sure that your program no longer has memory when
it exits.  (If the system _didn't_ do that, a program that crashed between
the malloc( ) and the free( ) would eat up some of main memory every time
it was run.)

I don't want to encourage sloppy programming :-), so I'll say you should
always free( ) any memory you malloc( ).  But in the interests of accuracy,
I'll have to add that on many (most?) systems there's probably no penalty
if you fail to do so.  Of course, if your program iss doing a great many
malloc( )s it may run out of memory and _have_ to do some free( )s to make
space available for more malloc( )s.

Stan Brown, Oak Road Systems, Cleveland, Ohio, U.S.A.         (216) 371-0043

Oak Road Systems stands behind my opinions 100%  However, nobody stands
behind the opinions of Oak Road Systems but me.  Does this tell you
something?



More information about the Comp.lang.c mailing list