malloc free
/* * File: alloc.c * Purpose: generic malloc() and free() engine * * Notes: 99% of this code stolen/borrowed from the K&R C * examples. * */ #include "common.h" #include "stdlib.h" #pragma section = "HEAP" /********************************************************************/ /* * This struct forms the minimum block size which is allocated, and * also forms the linked list for the memory space used with alloc() * and free(). It is padded so that on a 32-bit machine, all malloc'ed * pointers are 16-byte aligned. */ typedef struct ALLOC_HDR { struct { struct ALLOC_HDR *ptr; unsigned int size; } s; unsigned int align; unsigned int pad; } ALLOC_HDR; static ALLOC_HDR base; static ALLOC_HDR *freep = NULL; /********************************************************************/ void free( void *ap ) { ALLOC_HDR *bp, *p; bp = (ALLOC_HDR *) ap - 1; /* point to block header */ for ( p = freep; !( ( bp > p ) && ( bp < p->s.ptr ) ); p = p->s.ptr ) { if ( ( p >= p->s.ptr ) && ( ( bp > p ) || ( bp < p->s.ptr ) ) ) { break; /* freed block at start or end of arena */ } } if ( ( bp + bp->s.size ) == p->s.ptr ) { bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else { bp->s.ptr = p->s.ptr; } if ( ( p + p->s.size ) == bp ) { p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else { p->s.ptr = bp; } freep = p; } /********************************************************************/ void * malloc( unsigned nbytes ) { /* Get addresses for the HEAP start and end */ char* __HEAP_START = __section_begin("HEAP"); char* __HEAP_END = __section_end("HEAP"); ALLOC_HDR *p, *prevp; unsigned nunits; nunits = ( ( nbytes + sizeof(ALLOC_HDR) - 1 ) / sizeof(ALLOC_HDR) ) + 1; if ( ( prevp = freep ) == NULL ) { p = (ALLOC_HDR *) __HEAP_START; p->s.size = ( ( (uint32) __HEAP_END - (uint32) __HEAP_START ) / sizeof(ALLOC_HDR) ); p->s.ptr = &base; base.s.ptr = p; base.s.size = 0; prevp = freep = &base; } for ( p = prevp->s.ptr;; prevp = p, p = p->s.ptr ) { if ( p->s.size >= nunits ) { if ( p->s.size == nunits ) { prevp->s.ptr = p->s.ptr; } else { p->s.size -= nunits; p += p->s.size; p->s.size = nunits; } freep = prevp; return (void *) ( p + 1 ); } if ( p == freep ) return NULL; } } /********************************************************************/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本