void *malloc(size_t size) { t_block ptr, last; size_t temp_s = size; if (first_block) { /*First find a block*/ printf("mark first_block is not NULL now.\n"); last = first_block; ptr = find_block(&last, temp_s); /*split if yes*/ if (ptr) { printf("mark start of split_block"); if((ptr->size - temp_s) >= BLOCK_SIZE + 1) split_block(ptr, temp_s); ptr->is_free = FREE_N; } else { /*No fitting block, extend it*/ printf("====extend block because theres no fit block====\n"); ptr = extend_block(last, temp_s); if(!ptr) { fprintf(stderr, "extend block failed because of{ %s }\n", strerror(errno)); return NULL; } } } else { /*first time to allocate memory*/ ptr = extend_block(NULL, temp_s); if(!ptr) return NULL; first_block = ptr; } printf("====end of page ====\n"); return (void*)ptr->data; }
void *best_fit_realloc(t_ctx *ctx, void *p, size_t size) { t_mblk *block; void *np; (void)ctx; if (!p) return (ctx->fn.malloc(ctx, size)); if (!best_fit_valid_pointer(ctx, p)) return (NULL); size = ALIGN4(size); block = BLOCK_PTR(p); if (check_extend_block(ctx, block, size)) return (extend_block(ctx, block, size)); np = ctx->fn.malloc(ctx, size); memcpy(np, p, MIN(block->size, size)); ctx->fn.free(ctx, p); return (np); }