这是pbuf.c中函数pbuf_alloc中的一部分:
case PBUF_RAM:
/* If pbuf is to be allocated in RAM, allocate memory for it. */
p = (struct pbuf*)mem_malloc(LWIP_MEM_ALIGN_SIZE(SIZEOF_STRUCT_PBUF + offset) + LWIP_MEM_ALIGN_SIZE(length));###
if (p == NULL) {
return NULL;
}
/* Set up internal structure of the pbuf. */
p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + SIZEOF_STRUCT_PBUF + offset));###
p->len = p->tot_len = length;
p->next = NULL;
p->type = type;
我感觉后面加“###”的2句可能会有问题,LWIP_MEM_ALIGN_SIZE是长度按4字节对齐,LWIP_MEM_ALIGN是地址按4字节对齐。
假如SIZEOF_STRUCT_PBUF + offset
和length已经是按4字节对齐的了,此时分配的内存的大小就有可能正好是SIZEOF_STRUCT_PBUF + offset + length
,但是有可能p + SIZEOF_STRUCT_PBUF + offset
的地址不是按照4字节对齐的,这就导致p->payload
到pbuf的末尾的长度小于length,从而导致溢出。
因此,我觉得
p = (struct pbuf*)mem_malloc(LWIP_MEM_ALIGN_SIZE(SIZEOF_STRUCT_PBUF + offset) + LWIP_MEM_ALIGN_SIZE(length));
改成如下比较好:
p = (struct pbuf*)mem_malloc(LWIP_MEM_ALIGN_SIZE(SIZEOF_STRUCT_PBUF + offset) + LWIP_MEM_ALIGN_SIZE(length) + LWIP_MEM_ALIGN_SIZE(1));
其它不变,这样分配的pbuf多出4字节,能够避免溢出