为什么malloc使用的空间远远大于实际申请的空间?
程序代码:
// 目的:malloc 函数实现方式探索 // 平台:VC6.0 20100815 #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <assert.h> char *Alloc_CHAR_Array(long length) { char *array = NULL; if( NULL == (array = (char *)malloc(sizeof(char) * length) ) ) { fprintf(stdout, "Merory Exhausted\n"); return NULL; } //memset(array, 0, length*sizeof(double)); return array; } void Free_Array (char **array) { assert( array != NULL); printf("array=0x%p,*array=0x%p\n",array,*array); free(*array); } int main() { char *p1 = Alloc_CHAR_Array(0x100); char *p2 = Alloc_CHAR_Array(0x100); printf("p1=0x%p,p2=0x%p\n",p1,p2); p1[0] = '1'; p2[0] = '2'; // 验证 Free_Array 正确的释放了空间 Free_Array(&p1); p1 = Alloc_CHAR_Array(0x100); p1[0] = '1'; p2[0] = '2'; printf("p1=0x%p,p2=0x%p\n",p1,p2); // Free_Array(&p2); p2 = Alloc_CHAR_Array(0x90); printf("p1=0x%p,p2+0x90=0x%p\n",p1,p2+0x90); char *p3 = Alloc_CHAR_Array(0x10); printf("p1=0x%p,p2=0x%p,p3=0x%p\n",p1,p2,p3); printf("p1=0x%p,p3+0x10=0x%p\n",p1,p3+0x10); p3 = Alloc_CHAR_Array(0x10); printf("p1=0x%p,p2=0x%p,p3=0x%p\n",p1,p2,p3); return 0; }
发现实际申请的 0x10 字节空间,在malloc申请时总被占用0x38 个字节的存储空间!