cpointersmemorymallocheap-memory

Why in memory address have gap?


I wrote this code

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

int main() {
    int *ptr = malloc(10 * sizeof(int)); // 40 bytes 2940229680 - 2940229719
    printf("%p\n", ptr);
    char *block1 = (char *)malloc(10); // 10 bytes 2940229728 - 2940229737
    printf("%p\n", block1);
    void *block2 = malloc(10); // 10 bytes 2940229744 - 2940229753
    printf("%p\n", block2);
    return 0;
}

As you can see unlike my expectations second and third allocated places are not in a row. They have gap between their address. For example i thought block1 variable will use after 2940229720. But it use 2940229728. Can you explain why?

Exp. of why address are acting like that.


Solution

  • Memory management needs metadata. If you call free() on a pointer, it needs to figure out how much memory to release (among other things). Where this information is stored is up to the implementation of the C standard library, but allocating a few extra bytes and putting the data right there is a common approach.

    Do not, ever assume anything about how or where malloc() will put these gaps, or what is put inside them. This space is reserved to the library, and nothing good will come from poking around in it. Your space to use is the pointer malloc() returned to you, to the size you allocated. Everything else is strictly off-limits.

    If you need contiguous memory, you need to allocate it as such, and manage it yourself. Do not try this unless you have a pressing need. The standard library will, in almost every conceivable case, be more efficient about memory handling than you will.