⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 malloc.c

📁 ADS下的bios工程
💻 C
字号:
#include <bios/malloc.h>#include <bios/system.h>#include <bios/stdio.h>#undef DEBUG#ifdef DEBUG#define PRINTF(fmt, args...) printf("%s-%s()[%d]: " fmt, __FILE__, \      __FUNCTION__, __LINE__, ##args)#else#define PRINTF(fmt, args...)#endifstruct free {    int    size;    struct free    *next;};#define ALLOC_SIZE	0x4000static struct free    *free_list;static unsigned char    alloc_buf[ALLOC_SIZE];void malloc_init(void){    free_list = (struct free *)alloc_buf;    free_list -> next = NULL;    free_list -> size = ALLOC_SIZE;    PRINTF("BIOS free mem start(0x%x) \n", free_list);    PRINTF("BIOS free mem size(%d Kbytes)\n ", free_list -> size / 1024);}void *malloc(int size){    struct free    *tf;    void    *ptr;    flags_t    flags;    ptr = (void *)NULL;    /* aligned memage */    size = (size + 19) & ~15;    PRINTF("will malloc %d bytes\n", size);    save_flags(flags);    cli();    tf = free_list;    PRINTF("alloced block at 0x%p size %d, next(0x%x)\n", tf,            tf -> size, tf -> next);    if (tf -> size >= size + sizeof(struct free)) {        tf -> next = (struct free *)((int)tf + (size + sizeof(struct free)));        free_list = tf -> next;        free_list -> next = NULL;        free_list -> size = tf -> size - size;        tf -> size = size;        ptr = tf;    }     else {        PRINTF("%s", "exact!\n");        return  0;    }    ptr += sizeof(struct free);    restore_flags(flags);    PRINTF("will malloced %p \n", ptr);    return  ptr;}voidfree(void *ptr){    struct free    *tf, *nf, *ff;    flags_t    flags;    if (!ptr)         return ;    tf = (struct free *)((int)ptr - 8);	/* current free buffer point */    nf = (struct free *)alloc_buf;    PRINTF("freeing %p (block at %p, size %d, next 0x%x)\n", ptr, tf,           tf -> size, tf -> next);    save_flags(flags);    cli();    ff = (struct free *)tf -> next;		/* next free buffer point */    if (tf == (struct free *)alloc_buf) {        if (!(ff -> next)) {             tf -> size += (int)(ff -> size);            free_list = (struct free *)alloc_buf;        }    }     else {        nf -> size += tf -> size;        if (!(ff -> next)) {            nf -> size += ff -> size;            free_list = (struct free *)alloc_buf;        }    }    tf -> next = NULL;    restore_flags(flags);}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -