Malloc Header Content

Thus, in most implementations, malloc stores a header in front of the allocated memory to track the allocated memory (so that it can do free and rememberoc). What is the content of the header?

I wrote naive code to find it, but that makes no sense

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

He returns

Header = 57

What's going on here?

+5
source share
6 answers

I assume that you want to learn and see how memory is allocated. I would ignore Undefined Behavior answers. They are right (of course) when you talk about mobility and the like, but that is not your question. I think it’s a really good idea to try to figure out how distribution works.

malloc . , , , , google , .

linux, malloc glibc uclibc. uclibc: http://git.uclibc.org/uClibc/tree/libc/stdlib/malloc/malloc.c , .

http://git.uclibc.org/uClibc/tree/libc/stdlib/malloc/malloc.h 104. , . , MALLOC_HEADER_SIZE, . , , , ( ).

, uclibc, ...

+11

( , ), , , - undefined.

.

, , , (, 4 int). char* ( ) :

struct Foo * f = malloc(sizeof(Foo) * 7);
const unsigned char * const i_know_what_im_doing = f;

printf("%02X\n", *(i_know_what_im_doing - 1));
+4

, "57", .

, malloc calloc, , " ".

12 ints, int () 4 . 12x4 = 48. 4 ( 57) , 52.
57?

, Malloc Calloc 8- , . 8 56.

, , 8, , 0. , C, 0 .

, 1 56, 57 int.

+4

Undefined .
- UB.

, , .

+1

int , , . , , !

, , , - Undefined !!

, , !

, , , , .

, .

But you can malloc larger than the size of the segment, they can be additional information stored in this header, now you can never!

0
source

This behavior is undefined. But to be completely honest, if you're ready to scratch the insides of malloc, the first thing you need to do is determine what your malloc does.

Once you determine this, you can do something more intelligent than just random access to memory beyond what you allocated (which is the problem here).

0
source

All Articles