Hey fellow C programmers, I am working on an assignment for school. We have to make a dynamic memory map. Rules:
- Only used <stdio.h>
- One global char[] of a defined MEM_SIZE
- Four functions we will use:
- void mem_init(void);
- void dump_mem_structs(void);
- void *my_malloc(size_t size);
- void my_free(void *ptr);
Mem_init initialises the variables for *my_malloc(size_t size) and for my_free(void *ptr). Variables used for memory management are not allowed to be created in main OR globally.
Dump_mem_structs shows the blocks that are in use.
*my_malloc returns a block of the global char[] as a ptr to be used. Malloc should keep track of what memory block is used and what is not.
my_free releases the memory that was claimed by *my_malloc.
Given prototype:
What I added so far:Code:void main(void)
{
void *p[10];
mem_init();
dump_mem_structs();
p[1] = my_malloc(5);
p[2] = my_malloc(3);
p[3] = my_malloc(6);
p[4] = my_malloc(4);
p[5] = my_malloc(2);
p[6] = my_malloc(6);
p[7] = my_malloc(3);
p[8] = my_malloc(3);
dump_mem_structs();
my_free(p[2]);
my_free(p[5]);
my_free(p[8]);
dump_mem_structs();
p[9] = my_malloc(4);
dump_mem_structs();
}
My problem is, I start out with only 1 free block of 100 bytes. Now in my current way I just rewrite that same block back to 5 bytes and the free 95 bytes just disappear. How can I make this work without declaring a global array of the struct?Code:#include <stdio.h>
#define MEM_SIZE 100
void mem_init(void);
void dump_mem_structs(void);
void *my_malloc(size_t size);
void my_free(void *ptr);
typedef struct memory_block {
int used;
int size;
//void *data;
} mem_block;
char RAM[MEM_SIZE];
... main ...
void mem_init(void) {
mem_block *ptr = (mem_block *)RAM;
ptr->size = MEM_SIZE;
ptr->used = 0;
return;
}
void dump_mem_structs(void) {
char *status;
mem_block *ptr = (mem_block *)RAM;
if (ptr->used == 0)
status = "Free";
else
status = "In use";
printf("Block of %5d bytes: %s\n", ptr->size, status);
return;
}
void *my_malloc(size_t size) {
int i;
mem_block *ptr = (mem_block *)RAM;
ptr->size = (ptr->size - size);
for (i = 0; i < size; i++) {
ptr->size = size;
}
return (p);
}
void my_free(void *ptr) {
return;
}
What I would have done was to #define AMOUNT_BLOCKS and build my code based on that. So void *p[10] would be void *p[AMOUNT_BLOCKS] and I'd define a global array mem_block blocks[AMOUNT_BLOCKS]. But that's not allowed..
Can't get my head around this one!