Home > front end >  Behind the scene allocation of memory on heap using malloc
Behind the scene allocation of memory on heap using malloc

Time:11-01

if a process request 1-24 bytes on heap why 32 bytes difference ?

if a process request 25-40 bytes on heap why 48 bytes difference ?

if a process request 41-56 bytes on heap why 64 bytes difference ?

Initial 8bytes is used to hold the length of the allocated memory

#include <stdio.h>
#include<stdlib.h>
int main()
{

  int size=41;
  char* c = (char*) malloc(size);//initial 8bytes used for length
  char* d = (char*) malloc(size);
  printf("a = %p\nb = %p\n difference is %d\n",c,d,d-c);
  free(c);
  free(d);

}

CodePudding user response:

Usually the function malloc is implemented such a way that it returns a chunk of memory multiple by the paragraph size equal to 16 bytes (this value can be equal to the value of alignof(max_align_t)). That is the allocated memory must be aligned for any allocated object.

  • Related