Heap Management
Implementing a heap using a linked liststruct block_info { int allocated; /* Is the block in use? */ char *address; /* The starting address of the block */ int size; /* The size of the block */ struct block_info *next; /* The next block */ };
#define HEAP_SIZE 2000 /* Size of the memory to manage */ struct block_info *Heap_blocks; /* Head of the linked list of blocks */ Heap_blocks = malloc(sizeof(block_info)); /* Allocate the struct to manage the memory allocated above */ Heap_blocks->allocated = 0; /* It's currently all available */ Heap_blocks->address = malloc(HEAP_SIZE); /* Allocate the actual memory */ Heap_blocks->size = HEAP_SIZE; /* The total size of the memory */ Heap_blocks->next = NULL; /* The next block */
- More details about the structure layout in memory (comparing 32-bit with 64-bit computers):
Given this information, a more efficient way to layout the structure is like this:
32-bit system
(logical view)32-bit system
(physical view)
16 bytes64-bit system
(logical view)64-bit system
(physical view)
32 bytes Visually (24 bytes):struct block_info { int allocated; /* Is the block in use? */ int size; /* The size of the block */ char *address; /* The starting address of the block */ struct block_info *next; /* The next block */ };You can have gcc alert (warn) you when the compiler is adding padding between the fields of a struct. Just use the -Wpadded option when compiling the code. The message from gcc when compiling the original struct above looks like this:
struct.c:4:9: warning: padding struct to align 'address' [-Wpadded] char *address; ^~~~~~~ struct.c:6:22: warning: padding struct to align 'next' [-Wpadded] struct block_info *next; ^~~~