LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1398|回复: 3

关于malloc的问题

[复制链接]
发表于 2007-6-11 23:14:09 | 显示全部楼层 |阅读模式
#include<stdio.h>
void  main()
{void  *p,*q;
  int  m=30,n=0;
  p=(void  *)malloc(n);
  for(n=1;n<=m;n++)
    {q=p;
      p=(void  *)malloc(n);
      printf("malloc(%d)=%p,malloc(%d)=%p,the  increase  is  %d\n",n-1,q,n,p,p-q);
      }
}


输出结果:
malloc(0)=0x86f6008,malloc(1)=0x86f6018,the  increase  is  16
malloc(1)=0x86f6018,malloc(2)=0x86f6028,the  increase  is  16
malloc(2)=0x86f6028,malloc(3)=0x86f6038,the  increase  is  16
malloc(3)=0x86f6038,malloc(4)=0x86f6048,the  increase  is  16
malloc(4)=0x86f6048,malloc(5)=0x86f6058,the  increase  is  16
malloc(5)=0x86f6058,malloc(6)=0x86f6068,the  increase  is  16
malloc(6)=0x86f6068,malloc(7)=0x86f6078,the  increase  is  16
malloc(7)=0x86f6078,malloc(8)=0x86f6088,the  increase  is  16
malloc(8)=0x86f6088,malloc(9)=0x86f6098,the  increase  is  16
malloc(9)=0x86f6098,malloc(10)=0x86f60a8,the  increase  is  16
malloc(10)=0x86f60a8,malloc(11)=0x86f60b8,the  increase  is  16
malloc(11)=0x86f60b8,malloc(12)=0x86f60c8,the  increase  is  16
malloc(12)=0x86f60c8,malloc(13)=0x86f60d8,the  increase  is  16
malloc(13)=0x86f60d8,malloc(14)=0x86f60f0,the  increase  is  24
malloc(14)=0x86f60f0,malloc(15)=0x86f6108,the  increase  is  24
malloc(15)=0x86f6108,malloc(16)=0x86f6120,the  increase  is  24
malloc(16)=0x86f6120,malloc(17)=0x86f6138,the  increase  is  24
malloc(17)=0x86f6138,malloc(18)=0x86f6150,the  increase  is  24
malloc(18)=0x86f6150,malloc(19)=0x86f6168,the  increase  is  24
malloc(19)=0x86f6168,malloc(20)=0x86f6180,the  increase  is  24
malloc(20)=0x86f6180,malloc(21)=0x86f6198,the  increase  is  24
malloc(21)=0x86f6198,malloc(22)=0x86f61b8,the  increase  is  32
malloc(22)=0x86f61b8,malloc(23)=0x86f61d8,the  increase  is  32
malloc(23)=0x86f61d8,malloc(24)=0x86f61f8,the  increase  is  32
malloc(24)=0x86f61f8,malloc(25)=0x86f6218,the  increase  is  32
malloc(25)=0x86f6218,malloc(26)=0x86f6238,the  increase  is  32
malloc(26)=0x86f6238,malloc(27)=0x86f6258,the  increase  is  32
malloc(27)=0x86f6258,malloc(28)=0x86f6278,the  increase  is  32
malloc(28)=0x86f6278,malloc(29)=0x86f6298,the  increase  is  32
malloc(29)=0x86f6298,malloc(30)=0x86f62c0,the  increase  is  40


我的问题是:这个大小是怎么确定的呢?为什么不直接是n的大小,还有在malloc(13)的时候为什么增量是24呢,16不是也够吗?
怎么理解呢?
发表于 2007-6-12 19:01:55 | 显示全部楼层
主要是由于字节对齐的原因. 具体在实现这个函数的时候涉及到了一些结构体,而结构体中对于变量的分配涉及到字节需要对齐,所以说就不能直接为n的大小.
一个比较简单的例子就是

  1. struct a
  2. {
  3. int i;
  4. char c;
  5. long l;
  6. };
复制代码

其大小就不是简单的相加,而在malloc中就会出现结构体.所以说会出现你说的那种情况.
不过具体和平台相关.要想完全了解,只有去看具体实现代码了.
回复 支持 反对

使用道具 举报

 楼主| 发表于 2007-6-12 20:59:28 | 显示全部楼层
非常感谢。。。
回复 支持 反对

使用道具 举报

发表于 2007-6-14 03:41:27 | 显示全部楼层
还有在malloc(13)的时候为什么增量是24呢
注意对每个用malloc分配的块,malloc还需要一些额外的内存单元来管理这些块。可以猜测在你的平台上,malloc使用的额外字节数是4个字节(16-12),并且对齐的最小单位是8。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表