I think you need to be clear on something... You wouldn't be strictly allocating memory from this 1MB again. You would be simulating it instead... kind of writing a memory manager over top of the existing memory manager.
without thinking about it too much...
1. Lets say you have 1000 bytes of memory allocated for your memory pool (I pick 1000 because its a nice round number).
2. You need to keep track of which bytes are "allocated" and to which process. Sounds like a structure to me...
Code:
#define MEM_SIZE 1000
#define FALSE 0
#define TRUE 1
typedef struct mem_block{
int Is_Allocated;
int Process_ID;
} mem_block;
char block[MEM_SIZE]; // I'm using a predetermined size, but mem_block *block = malloc(MEM_SIZE); would work too
mem_block block_track[MEM_SIZE];
3. Now when a process requests a block of memory, you have to search for a contiguous chunk of memory in some sort of loop. So you need your own version of the malloc() function
Code:
char * my_malloc(int size, int process_id) {
int Block_Index = 0;
int Size_Count = 0;
int Start_Index = 0;
while (Block_Index < MEM_SIZE) {
if (block[Block_Index].Is_Allocated == TRUE) {
Size_Count = 0; // Reset Size Count
Block_Index++;
Start_Index = Block_Index;
} else {
Size_Count++;
}
if (Size_Count == size) break; // We have found a chunk big enough!
}
// Now check Size_Count to see if we found one big enough...
if (Size_Count == size) {
// We did! Now allocate the memory block
for (Block_Index = Start_Index; Block_Index < Start_Index + size; Block_Index++) {
block[Block_Index].Is_Allocated = TRUE;
block[Block_Index].Process_ID = process_id;
}
// Now return a pointer to the starting point of the memory block
return &(block[Block_Index]); // I'm not 100% sure if this is correct...
} else {
// We didnt :( return a null pointer
return 0;
}
}
Now you'll need to write a free() function to deallocate the memory when necessary.