美文网首页
2019-06-15

2019-06-15

作者: 阿群1986 | 来源:发表于2019-06-15 18:38 被阅读0次

微软vs2012中malloc()的实现是在申请的内存前面加上4个字节放长度和其它的一些信息。
这样free的时候就只需要把指针传进去,往前找几个字节,获取相关信息,然后删掉对应的空间即可。

而GCC下虽然也是把malloc的相关信息放在前面,不过数据格式和vs的不一样。

可以试试

#include <stdio.h>
int main(){

int *newtarr = malloc(8);
printf("malloc(8)向左偏移2个int32: 0x%08X\n", newtarr[-2]);
printf("malloc(8)向左偏移2个int32: 0x%08X\n", newtarr[-2]);

realloc(newtarr, 4);

newtarr = malloc(2);
printf("malloc(2): 0x%08X\n", newtarr[-2]);
free(newtarr);

newtarr = malloc(4);
printf("malloc(4)结果: 0x%08X\n", newtarr[-2]);
free(newtarr);

newtarr = malloc(8);
printf("malloc(8)结果: 0x%08X\n", newtarr[-2]);
free(newtarr);

}

相关文章

网友评论

      本文标题:2019-06-15

      本文链接:https://www.haomeiwen.com/subject/anfifctx.html