0

My understanding is that malloc internally uses sbrk() and sbrk(0) gives pointer to current location of the program break. then according to following code :-

#include<stdio.h>
#include<malloc.h>
int main()
{
    printf("Before allocation :- %u\n",sbrk(0));

    int *ptr = malloc(sizeof(int)*100);
    printf("After Allocation of 400Bytes :- %u\n",sbrk(0));

    free(ptr);
    printf("After free() :- %u\n",sbrk(0));

    return 0;
}

output is :

Before allocation :- 37367808
After Allocation of 400Bytes :- 37502976
After free() :- 37502976

But after call of free() it should print again 37367808 instead it is printing 37502976.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • Without knowing for sure, this is likely because of what the program break represents for the operating system. The break represents the end of the initialised parts of the data segment of the program. After a free the OS might consider the area initialised and not reduce the decrement the program break. – Hans Petter Taugbøl Kragset Sep 27 '17 at 15:17
  • `malloc` often uses `mmap` and prefer to re-use previously `free`-d memory – Basile Starynkevitch Sep 27 '17 at 15:49
  • According to my understanding the initially data-segment size is small(may also be of size zero). But when you `malloc` if memory's not available in program's data-segment then CRT uses the sbrk/brk to enlarge its data-segment. And `free` in CRT may be implemented so that it doesn't return/free small chunks back to OS as to reduce the overhead (as system calls have more overhead compared to these CRT internals). – Madhusoodan P Oct 03 '17 at 12:22

0 Answers0