版权所有,转载请注明出处,谢谢!
http://blog.csdn.net/walkinginthewind/article/details/7069176
我们都知道,C语言中要动态申请内存需要调用malloc函数,释放动态内存需要调用free函数。内存的申请与释放都是在堆(Heap)上进行的。当然,所谓的内存,都是虚拟内存。
C语言中的malloc和free,在windows中主要是通过HeapAlloc和HeapFree来实现的。typedef struct _RTL_HEAP_ENTRY { SIZE_T Size; // 指示该段内存的大小 USHORT Flags; USHORT AllocatorBackTraceIndex; union { struct { SIZE_T Settable; ULONG Tag; } s1; // All other heap entries struct { SIZE_T CommittedSize; PVOID FirstBlock; } s2; // RTL_SEGMENT } u; } RTL_HEAP_ENTRY, *PRTL_HEAP_ENTRY;
#include<stdio.h> #include<windows.h> typedef struct _RTL_HEAP_ENTRY { SIZE_T Size; USHORT Flags; USHORT AllocatorBackTraceIndex; union { struct { SIZE_T Settable; ULONG Tag; } s1; struct { SIZE_T CommittedSize; PVOID FirstBlock; } s2; } u; } RTL_HEAP_ENTRY, *PRTL_HEAP_ENTRY; int main() { PRTL_HEAP_ENTRY pHeapEntry; int *p; for(int i = 0; i < 1000; i++) { p=(int*)malloc(i); pHeapEntry=(PRTL_HEAP_ENTRY(p)-1); printf("i: %d, size: %d\n", i, pHeapEntry->Size); free(p); } return 0; }
输出结果是:
i: 0, size: 0
i: 1, size: 1
i: 2, size: 2
...
i: 999, size: 999
总结:本文根据windows源码简单的分析了windows对C库函数free的实现中对内存大小信息的记录方法。