cmemorymallocmemory-alignment

Why does malloc(10) allocate 24 bytes?


I am experimenting with malloc in C to better understand how memory alignment and allocation actually work behind the scenes. Here is the simple code I am running:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

int main() {
    void* p1 = malloc(10);
    void* p2 = malloc(10);
    size_t actual_size = malloc_usable_size(p1);

    printf("p1 points to: %p \np2 points to: %p \n", p1, p2);
    printf("Actual size of p1: %zu\n", actual_size);

    return 0;
}

And here is the output:

p1 points to: 0x5637af0252a0 
p2 points to: 0x5637af0252c0 
Actual size of p1: 24

I understand that memory allocation usually includes some overhead or padding for alignment, but I’m trying to learn exactly why malloc(10) results in an allocation of 24 bytes in this case.

This post mentions that allocation size is "24 + 16n". I get the same sequence of numbers. I know these extra bytes are implementation specific, and are they exist to aid memory management, but I was wondering if someone knows specific details about those extra bytes and their content.

Notes:

Any insights into how malloc decides the actual allocation size would be appreciated!


Solution

  • if we look at the malloc function written in malloc.h, we have the answer to this.

    see.
    https://github.com/lattera/glibc/blob/895ef79e04a953cac1493863bcae29ad85657ee1/malloc/malloc.c#L487

    /*
      malloc(size_t n)
      Returns a pointer to a newly allocated chunk of at least n bytes, or null
      if no space is available. Additionally, on failure, errno is
      set to ENOMEM on ANSI C systems.
    
      If n is zero, malloc returns a minumum-sized chunk. (The minimum
      size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
      systems.)  On most systems, size_t is an unsigned type, so calls
      with negative arguments are interpreted as requests for huge amounts
      of space, which will often fail. The maximum supported value of n
      differs across systems, but is in all cases less than the maximum
      representable value of a size_t.
    */
    void*  __libc_malloc(size_t);
    libc_hidden_proto (__libc_malloc)