Skip to content

Commit

Permalink
Cleanup malloc for better grab/release count consistency
Browse files Browse the repository at this point in the history
  • Loading branch information
mesheets committed Jul 27, 2024
1 parent b11cf16 commit 75ad4fc
Showing 1 changed file with 26 additions and 25 deletions.
51 changes: 26 additions & 25 deletions kernel/mm.c
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ __TEXT_INIT__ void mm_init() {
\return 0 on error, else pointer to block.
*/
void *malloc(size_t size) {
void *mem_block = NULL;
meminfo_t *ptr;
meminfo_t **pptr;

Expand All @@ -135,32 +136,32 @@ void *malloc(size_t size) {
pptr = &mm_first_free;

while((ptr = *pptr)) {
int blocksize = ((void*)ptr->next - (void*)ptr);
/* big enough? */
if (blocksize >= size + MM_HEADER_SIZE) {
/* set flags */
ptr->flags = (ctid->tflags & T_KERNEL) ? MM_KERNEL : MM_USER;

/* split this block? */
if(blocksize >= size + MM_SPLIT_THRESH) {
meminfo_t *next = (meminfo_t*) ((size_t)ptr + (size + 4));
next->flags = MM_FREE;
next->next = ptr->next;
ptr->next->prev = next;
next->nextfree = ptr->nextfree;
ptr->next = next;
*pptr = next;
} else {
ptr->next->next = (void*) ((size_t) ptr->next->next & ~1);
*pptr = ptr->nextfree;
}
release_kernel_lock();
return (void*) &(ptr->nextfree);
}
pptr = &ptr->nextfree;
}
int blocksize = ((void*)ptr->next - (void*)ptr);
/* big enough? */
if (blocksize >= size + MM_HEADER_SIZE) {
/* set flags */
ptr->flags = (ctid->tflags & T_KERNEL) ? MM_KERNEL : MM_USER;

/* split this block? */
if(blocksize >= size + MM_SPLIT_THRESH) {
meminfo_t *next = (meminfo_t*) ((size_t)ptr + (size + 4));
next->flags = MM_FREE;
next->next = ptr->next;
ptr->next->prev = next;
next->nextfree = ptr->nextfree;
ptr->next = next;
*pptr = next;
} else {
ptr->next->next = (void*) ((size_t) ptr->next->next & ~1);
*pptr = ptr->nextfree;
}
mem_block = (void*) &(ptr->nextfree);
break;
}
pptr = &ptr->nextfree;
}
release_kernel_lock();
return NULL;
return mem_block;
}

//! free a previously allocated block of memory.
Expand Down

0 comments on commit 75ad4fc

Please sign in to comment.