cmallocsbrk

Why malloc and sbrk returns address from seperate segments?


I am trying to implement understand how dynamic memory allocation is happening. So I thought of implementing malloc of my own using sbrk() system call. My Question here is when i try to allocate dynamic memory, sbrk() and malloc() returns different addresses not continuous.

Here is my code

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

int main(int argc, char** argv)
{
    printf("\nsbrk(0) %llu ",(unsigned long long)sbrk(0));
    printf("\nmalloc(8) %llu ",(unsigned long long)malloc(8));
    printf("\nmalloc(8) %llu ",(unsigned long long)malloc(8));
    printf("\nsbrk(8) %llu ",(unsigned long long)sbrk(8));
    printf("\nmalloc(8) %llu ",(unsigned long long)malloc(8));
    printf("\nmalloc(8) %llu ",(unsigned long long)malloc(8));  
    printf("\n");
    return 0;
}

Output of the above code is

sbrk(0) 30306304 
malloc(8) 30306320 
malloc(8) 30306352 
sbrk(8) 30441472 
malloc(8) 30306384 
malloc(8) 30306416 

Can anyone explain why sbrk(8) is not continuous locations.


Solution

  • The standard does not give any guarantee for the contiguity of storage even for memory allocated by successive calls to malloc. So the different calls to malloc in your code need not yield contiguous locations.

    The C11 standard states:

    7.22.3 Memory management functions

    1. The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc, malloc, and realloc functions is unspecified.

    And the addresses that come from the mixing up of malloc and sbrk calls need not be contiguous either.