Liu said:
From memory management perspective, how to code in c to create a > managed
heap that can be extended and shrunk ?The basic way to implement a meory allocation scheme is to declare an arena
static BLOCK arena[100000];
You then allocate blocks which consist of
typedef struct block
{
struct block *next;
size_t size;
}BLOCK;
The free list consists of a linked list of a a series of blocks. Initially
the whole arena is one big free block. When you allocate, walk the free
list until you find a block that is large enough. Then you spilt it and
return the pointer that is immediately after the control block.
When you free, walk the free list until you find the place where the ponter
is greater than the preceding and less than the following block, then you
have to add the block to the free list and consolidate if possible.
The trick is that you always return the control block +1, so the size is
always stored immediately before the memory you allocate.
If you know the arena size at compile time, simply hard code it in. If you
have to query the operating system to know how much memory you are allowed
to use, you leave the realms of comp.lang.c, and you will have to ask in a
platform-specific group.