lwip-mem_init和mem_malloc详解

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

lwip-mem_init和mem_malloc详解

[cpp] view plain copy <pre name="code"

class="cpp">#define MEM_ALIGNMENT 4

//对齐方式为4字节对齐#ifndef LWIP_MEM_ALIGN_SIZE #define LWIP_MEM_ALIGN_SIZE(size) (((size) +

MEM_ALIGNMENT - 1) & ~(MEM_ALIGNMENT-1)) //实现待分配数据空间的内存对齐#endif #ifndef LWIP_MEM_ALIGN //地址对齐,对齐方式也为4字节对齐#define LWIP_MEM_ALIGN(addr) ((void

*)(((mem_ptr_t)(addr) + MEM_ALIGNMENT - 1) &

~(mem_ptr_t)(MEM_ALIGNMENT-1))) #endif /* MEM_SIZE: the size of the heap memory. If the application will send a lot of data that needs to be copied, this should be set high. */ #define MEM_SIZE (8*1024) //堆的总空间大小,此后在这个基础上划分堆,将在这个空间进行内存分配,内存块结构体和数据都是在这个空间上的

//mem为内存块的结构体,next;,prev都为内存块索引struct mem { /** index (-> ram[next]) of the next struct */

//ram为堆的首地址,相当于数组的首地址,索引基地址mem_size_t next; //next为下一个内存块的索引/** index (-> ram[next]) of the next struct */

mem_size_t prev; //prev为前一个内存块的索引/** 1: this area is used; 0: this area is unused */ u8_t used;

//标志此内存块已被分配}; static struct mem *ram_end; /** All allocated blocks will be MIN_SIZE bytes big, at least!

* MIN_SIZE can be overridden to suit your needs. Smaller values save space, * larger values could prevent too small blocks to fragment the RAM too much. */ #ifndef MIN_SIZE #define MIN_SIZE 12 //内存块大小的最小限制,不能小于12 #endif /* MIN_SIZE */ /* some alignment macros: we define them here for better source code layout */ #define MIN_SIZE_ALIGNED

LWIP_MEM_ALIGN_SIZE(MIN_SIZE) //将MIN_SIZE

按4字节对齐,即把12按4字节对齐#define

SIZEOF_STRUCT_MEM

LWIP_MEM_ALIGN_SIZE(sizeof(struct mem)) //将mem大小按4字节对齐#define MEM_SIZE_ALIGNED

LWIP_MEM_ALIGN_SIZE(MEM_SIZE) //将堆的总空间按4字节对齐,MEM_SIZE在前面,为8*1024 //内存对齐解释看我的博文:

/lg2lh/article/details/34853883 /** the heap. we need one struct mem at the end and some room for

alignment */ static u8_t ram_heap[MEM_SIZE_ALIGNED + (2*SIZEOF_STRUCT_MEM) + MEM_ALIGNMENT]; //实际开的堆内存空间,MEM_SIZE_ALIGNED为对齐后的数据空间为8192 //堆内存的大小为

MEM_SIZE_ALIGNED+(2*SIZEOF_STRUCT_MEM)+MEM _ALIGNMENT=8192+2*MEN结构体的大小+4 void mem_init(void) { struct mem *mem; //定义一个mem 结构体指针变量LWIP_ASSERT("Sanity check alignment", (SIZEOF_STRUCT_MEM &

(MEM_ALIGNMENT-1)) == 0); /* align the heap */

ram = LWIP_MEM_ALIGN(ram_heap); //将堆空间首地址ram_heap按4字节地址对齐/* initialize the start of the heap */ mem = (struct mem *)ram; //将堆空间ram 首地址强制转换成mem结构体类型,作为首个内存块,但这个内存块还未使用mem->next =

MEM_SIZE_ALIGNED; //把首个内存块的next指针指向了堆空间的最后一个地址(MEM_SIZE_ALIGNED为8*1024),后面实际在mem_malloc时会动态调整next索引, //从而得到实际分配内存空间即为mem->next减去该内存块mem 的地址//待分配内存块的next索引总是指向堆空间最后,好像也不一定,但是按照思路是这样的。mem->prev = 0; //初始化,因为是第一个内存块,所以前一个内存块不存

相关文档
最新文档