Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc header contents

Tags:

c

malloc

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?

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));

It returns

Header = 57

What is happening here?

like image 552
Bruce Avatar asked Oct 10 '11 18:10

Bruce


People also ask

What header file contains malloc?

malloc is part of the standard library and is declared in the stdlib. h header.

What information can malloc return?

Return value malloc returns a void pointer to the allocated space, or NULL if there's insufficient memory available. To return a pointer to a type other than void , use a type cast on the return value.

What is inside malloc?

The malloc() function stands for memory allocation. It is a function which is used to allocate a block of memory dynamically. It reserves memory space of specified size and returns the null pointer pointing to the memory location. The pointer returned is usually of type void.

What memory does malloc allocate?

Malloc(12) and malloc(16) allocate 16 bytes for the user, plus an extra 8 bytes for bookkeeping for a total of 24 bytes. Malloc(100) allocates 104 bytes for the user, plus an extra 8 bytes for bookkeeping.


1 Answers

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.

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.

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.

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)

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

like image 78
Michel Avatar answered Oct 02 '22 02:10

Michel