Thanks! I made my code work a little better, but not fully functional yet.
Code:
#include <unistd.h>
#define MEM_SIZE 100
typedef struct memory_block {
int used;
int size;
} mem_block;
void my_malloc(size_t size);
void dump_mem_structs(void);
void mem_init(void);
mem_block *next_struct(mem_block *p_curr);
char RAM[MEM_SIZE];
int main() {
mem_init();
dump_mem_structs();
printf("\nAllocating new memory...\n\n");
my_malloc(5);
my_malloc(7);
my_malloc(9);
my_malloc(12);
my_malloc(5);
dump_mem_structs();
return 0;
}
void mem_init(void) {
printf("\nStart mem address: %p\nEnd mem address : %p\n\n", &RAM[0], &RAM[100]);
mem_block *ptr = (mem_block *)RAM;
ptr->size = MEM_SIZE;
ptr->used = 0;
return;
}
void my_malloc(size_t size) {
mem_block *ptr = (mem_block *)RAM;
while (ptr->used == 1) {
ptr = next_struct(ptr);
}
printf("Next pointer address: %p\n", ptr);
ptr->used = 1;
ptr->size = size;
return;
}
void dump_mem_structs(void) {
char *status;
mem_block *ptr = (mem_block *)RAM;
int curr_block_size = ptr->size + sizeof(mem_block);
while (&RAM[0] + curr_block_size <= (&RAM[MEM_SIZE] + sizeof(mem_block))) {
if (ptr->used == 0)
status = "Free";
else
status = "In use";
printf("Block of %5d bytes: %s\n", ptr->size + (int)sizeof(mem_block), status);
ptr = next_struct(ptr);
curr_block_size += (ptr->size + sizeof(mem_block));
}
return;
}
mem_block *next_struct(mem_block *p_curr) {
//printf("Address of argument: %p\nOne mem_block higher: %p\n", p_curr, p_curr + (int)(sizeof(mem_block)));
//printf("Size of mem_block: %d\n", (int)sizeof(mem_block));
//mem_block *ptr = (mem_block *)RAM;
//int next = p_curr->size + 1;//sizeof(mem_block);
mem_block *next = p_curr + sizeof(mem_block); //sizeof(mem_block);
return next;
//return (p_curr + next);
}
Excuse my comments, lol! My output is:
Next pointer address: 0x601080
Next pointer address: 0x6010c0
Next pointer address: 0x601100
And some more things. But these matter right now. Why does my function *next_struct increase my address by 64 every time it is called? Sizeof(mem_block) is 8. So shouldn't it go from 0x601080 to 0x601088?