免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 682 | 回复: 0
打印 上一主题 下一主题

2006.3.16 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-03-17 01:07 |只看该作者 |倒序浏览
参考文章: http://www.nsfocus.net/index.php?act=sec_doc&do=view&doc_id=901&keyword=
当 buf1 = malloc(32); 后,内存结构为:
buf1的管理结构(8bytes)|buf1真正可操作空间(32bytes)|下一个空闲堆的管理结构(8bytes)|两个双链表指针(8bytes)
但是我用:
int *buf1, *buf2;
  buf1 = malloc(32);
  buf2 = malloc(32);
  printf("buf1: %u, buf2: %u.\n", buf1, buf2);
  printf("two int before buf1: %u, %u.\n", buf1[-2], buf1[-1]);
  printf("four int after buf1: %u, %u, %u, %u.\n", buf1[8], buf1[9], buf1[10], buf1[11]);
  printf("two int before buf2: %u, %u.\n", buf2[-2], buf2[-1]);
  printf("four int after buf2: %u, %u, %u, %u.\n", buf2[8], buf2[9], buf2[10], buf2[11]);
得到的运行结果却为:
ammer@cj:~/tmp$ ./a.out
buf1: 134520840, buf2: 134520880.
two int before buf1: 0, 41.
four int after buf1: 0, 41, 0, 0.
two int before buf2: 0, 41.
four int after buf2: 0, 135089, 0, 0.
唯一看出的价值是 两次分配的内存段间空隙为 8 字节,且得到内存的前面8字节内容相同.
可以证实:
  int *buf1, *buf2, *buf3;
  buf1 = malloc(16);
  buf2 = malloc(32);
  buf3 = malloc(64);
  printf("buf1: %u, buf2: %u. buf3: %u\n", buf1, buf2, buf3);
  printf("two int before buf1: %u, %u. before buf2: %u, %u,
before buf3: %u, %u.\n", buf1[-2], buf1[-1], buf2[-2], buf2[-1],
buf3[-2], buf3[\-1]);
结果:
buf1: 134520840, buf2: 134520864. buf3: 134520904
two int before buf1: 0, 25. before buf2: 0, 41, before buf3: 0, 73.
看出: 1.分配的内存区前多出8个字节. 2.前一个数比分配大小大9.
     但改变分配的大小发现这个两个数都不固定,可能是字节对齐的需要.
原来此文为 windows 底下的分析 :(   明天继续
http://www.nsfocus.net/index.php?act=sec_doc&do=view&doc_id=753&keyword=malloc
http://www.nsfocus.net/index.php?act=sec_doc&do=view&doc_id=681&keyword=malloc
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/15482/showart_86577.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP