malloc的头内容 [英] Malloc header contents

查看:345
本文介绍了malloc的头内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,在大多数实现的malloc存储所分配的存储器前的首标来跟踪所分配的存储器的大小(以便它可以做自由和recalloc)。什么是头的内容?

So in most implementations malloc stores an header before the allocated memory to keep track of the allocated memory size (so that it can do free and recalloc). What are the header contents?

我写了一个天真code,以找到它,但它并没有任何意义。

I wrote a naive code to find it but it doesn't make any sense

int * ptr;
ptr = malloc(12*sizeof(int));
printf("Header = %d\n",*(ptr-1));

它返回

Header = 57

这是怎么回事?

推荐答案

我猜你想了解和看到内存是如何分配的。我会忽略未定义行为的答案。他们是正确的(当然)当你谈论的可移植性等,但不是你的问题。我认为这是一个很好的主意,试图找出分配是怎么做的。

I'm guessing you want to learn and see how the memory is allocated. I would ignore the Undefined Behaviour answers. They are right (of course) when you talk about portability and such, but that is not your question. I think it is a really good idea to try and figure out how the allocation is done.

首先,我建议你开始看你的平台上的malloc实现。如果code是不可用,你的运气了,唯一觉得你能做的就是为线索的分配是怎么做的谷歌。

First I would encourage you to start looking at the malloc implementation for your platform. If that code is not available, you are out of luck and the only think you can do is google for clues how the allocation is done.

如果你运行Linux,你可以看看的malloc实现的glibc或uClibc的的。下面的链接uClibc的实现:
<一href=\"http://git.uclibc.org/uClibc/tree/libc/stdlib/malloc/malloc.c\">http://git.uclibc.org/uClibc/tree/libc/stdlib/malloc/malloc.c
在code有很多评论,但可以是压倒性的。

If you run linux, you can look at the malloc implementation of glibc or uclibc. Here a link to the uclibc implementation: http://git.uclibc.org/uClibc/tree/libc/stdlib/malloc/malloc.c The code has lot of comments, but can be overwhelming.

对于你的问题,看看<一个href=\"http://git.uclibc.org/uClibc/tree/libc/stdlib/malloc/malloc.h\">http://git.uclibc.org/uClibc/tree/libc/stdlib/malloc/malloc.h上线104。
这是你正在谈论的一部分。你看布局取决于MALLOC_HEADER_SIZE它可以为不同的系统不同。通过阅读code你可以学习使用的类型,并在这抵消了内存大小存储(在这个特定的实现)

For your question, look at http://git.uclibc.org/uClibc/tree/libc/stdlib/malloc/malloc.h on line 104. which is the part you are talking about. You see the layout depends on MALLOC_HEADER_SIZE which can be different for different systems. By reading the code you can learn which types to use, and on which offset the memory size is stored (in this specific implementation)

当然,以上仅仅是从uClibc的一个示例实现,让你开始...

Of course, above is just an example implementation from uclibc to get you started...

这篇关于malloc的头内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆