堆管理之malloc和free分析

在win7 64环境下分析

1.malloc代码

int main()
{
void *p = malloc(0xa8);

memset(p, 'a', 0xa8);

free(p);
return 0;
}

2.malloc(windbg分析)

  • 函数调用过程

ntdll!RtlAllocateHeap//后面还有一串调用。过于复杂,不再跟进。
rpci!_malloc_base+0x44 [d: hminkernelcrtsucrtsrcappcrtheapmalloc_base.cpp @ 29]//call    qword ptr [rpci!_imp_HeapAlloc]
rpci!main+0x21//此处malloc(a8)
rpci!invoke_main+0x22 [f:ddvctoolscrtvcstartupsrcstartupexe_common.inl @ 64]
rpci!__scrt_common_main_seh+0x124 [f:ddvctoolscrtvcstartupsrcstartupexe_common.inl @ 255]
kernel32!BaseThreadInitThunk+0xd
ntdll!RtlUserThreadStart+0x1d

  • dc 004eb0a0

00000000`004eb0a0 feeefeee feeefeee 0b71f188 3800e716 ..........q....8//这里可以看出,堆头大小为0x10.
00000000`004eb0b0 baadf00d baadf00d baadf00d baadf00d ................
00000000`004eb0c0 baadf00d baadf00d baadf00d baadf00d ................//rax+a8后面也有一些堆尾数据

注意这是在windbg中启动程序运行。!gflag=0x70

如果直接运行,然后windbg附加到上面,则:!gflag=0

0:000> dd rax-10//可见,申请内存后,并没有初始化。
00000000`003f4260 00450042 002e003b 5f71a286 08003e99
00000000`003f4270 003f8000 00000000 003b0158 00000000
00000000`003f4280 002e003b 00530057 003b0048 004d002e
00000000`003f4290 00430053 00500000 004f0052 00450043

0:000> !heap -p -a rax//没开pageheap也可以查看
address 00000000003f4270 found in
_HEAP @ 3b0000
HEAP_ENTRY Size Prev Flags UserPtr UserSize - state
00000000003f4260 000b 0000 [00] 00000000003f4270 000a8 - (busy)//堆头大小为0x10

 3.memset填充数据

0:000> dc 0000000000404270 +a8-10
00000000`00404308 61616161 61616161 61616161 61616161 aaaaaaaaaaaaaaaa//一直到堆尾,最后没填0
00000000`00404318 b41d0acd 0000b0b4 00408000 00000000 
00000000`00404328 003c0158 00000000 00650074 00700070 
00000000`00404338 006e0069 00200067 002c0037 00470020
0:000> !heap -p -a 00404308
address 0000000000404308 found in
_HEAP @ 3c0000
HEAP_ENTRY Size Prev Flags UserPtr UserSize - state
0000000000404260 000b 0000 [00] 0000000000404270 000a8 - (busy)

0:000> !heap -p -a 00404318 //奇怪现象:挨着的地址为何堆头=被占用的地址。不对!
address 0000000000404318 found in
_HEAP @ 3c0000
HEAP_ENTRY Size Prev Flags UserPtr UserSize - state
0000000000404310 008b 0000 [00] 0000000000404320 008a0 - (free)

4.free.

0:000> dc 0000000000404270
00000000`00404270 00408000 00000000 003c0158 00000000 ..@.....X.<.....
00000000`00404280 61616161 61616161 61616161 61616161 aaaaaaaaaaaaaaaa//释放后数据并没有填0
00000000`00404290 61616161 61616161 61616161 61616161 aaaaaaaaaaaaaaaa
0:000> !heap -p -a 0000000000404270
address 0000000000404270 found in
_HEAP @ 3c0000
HEAP_ENTRY Size Prev Flags UserPtr UserSize - state
0000000000404260 0096 0000 [00] 0000000000404270 00950 - (free)//已经交给系统。

原文地址:https://www.cnblogs.com/studyskill/p/7388660.html