void *malloc(size_t size) { struct free_arena_header *fp; if (size == 0) return NULL; /* Add the obligatory arena header, and round up */ size = (size + 2 * sizeof(struct arena_header) - 1) & ~ARENA_SIZE_MASK; for (fp = __malloc_head.next_free; fp->a.type != ARENA_TYPE_HEAD; fp = fp->next_free) { if (fp->a.size >= size) { /* Found fit -- allocate out of this block */ return __malloc_from_block(fp, size); } } /* Nothing found... need to request a block from the kernel */ return NULL; /* No kernel to get stuff from */ }
void *malloc(size_t size) { struct free_arena_header *fp; struct free_arena_header *pah; size_t fsize; if (size == 0) return NULL; /* Add the obligatory arena header, and round up */ size = (size + 2 * sizeof(struct arena_header) - 1) & ARENA_SIZE_MASK; for (fp = __malloc_head.next_free; fp->a.type != ARENA_TYPE_HEAD; fp = fp->next_free) { if (fp->a.size >= size) { /* Found fit -- allocate out of this block */ return __malloc_from_block(fp, size); } } /* Nothing found... need to request a block from the kernel */ fsize = (size + MALLOC_CHUNK_MASK) & ~MALLOC_CHUNK_MASK; #if _KLIBC_MALLOC_USES_SBRK fp = (struct free_arena_header *)sbrk(fsize); #else fp = (struct free_arena_header *) mmap(NULL, fsize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); #endif if (fp == (struct free_arena_header *)MAP_FAILED) { return NULL; /* Failed to get a block */ } /* Insert the block into the management chains. We need to set up the size and the main block list pointer, the rest of the work is logically identical to free(). */ fp->a.type = ARENA_TYPE_FREE; fp->a.size = fsize; /* We need to insert this into the main block list in the proper place -- this list is required to be sorted. Since we most likely get memory assignments in ascending order, search backwards for the proper place. */ for (pah = __malloc_head.a.prev; pah->a.type != ARENA_TYPE_HEAD; pah = pah->a.prev) { if (pah < fp) break; } /* Now pah points to the node that should be the predecessor of the new node */ fp->a.next = pah->a.next; fp->a.prev = pah; pah->a.next = fp; fp->a.next->a.prev = fp; /* Insert into the free chain and coalesce with adjacent blocks */ fp = __free_block(fp); /* Now we can allocate from this block */ return __malloc_from_block(fp, size); }