[comp.lang.c] malloc and stuff

jdb@reef.cis.ufl.edu (Brian W.K. Hook) (11/26/90)

Small question....how does a C compiler or an operating system (whichever
is responsible) handle "memory fragmentatino".  Assume, for instance, that
you allocate 200 1K blocks of memory.  Then you free() every other block,
so that you 1K allocated, then 1K not, etc....Now, if all you have is 200K
available to your system, and you allocate now a 100K block (since you
theoretiocally have 100K available), wouldn't pointer arithmetic really
get screwed up?  Eg.. *(block2+1) wouldn't return something expected,
would it....or does the C compiler automatically generate code that 
compresses memory.  But if that is the case, what if you use absolute
addressing?  Or would it just say that you can't allocate that 100K block
at all since it isn't contiguous?

gwyn@smoke.brl.mil (Doug Gwyn) (11/27/90)

In article <25576@uflorida.cis.ufl.EDU> jdb@reef.cis.ufl.edu (Brian W.K. Hook) writes:
>Or would it just say that you can't allocate that 100K block
>at all since it isn't contiguous?

Correct.  malloc() allocates a single contiguous chunk of memory.
It cannot create one by moving earlier active allocations, because
the application holds pointers that wouldn't work after the move.
Thus, if not enough contiguous storage is already available, and
if there is no way to acquire more from the system (as via UNIX
sbrk()), malloc() simply reports failure.