Search code examples
carmmallocfree32-bit

usage of mallinfo in embedded systems


am trying to use the mallinfo struct to print the heap usage done through malloc information .. but am not able to find the exact match for each allocation below is the way I tried .

printMemoryInfo()
{
   struct mallinfo mi;
   memset(&mi,0,sizeof(struct mallinfo));
   mi = mallinfo();
   printf(" Heap Blocks = %d\n"mi.uordblks)
}


main()
{
  printf("Initial \n");
  printMemoryInfo();
  char * data = malloc(2); /* 2 bytes*/
  printf("After  Malloc 1");
  printMemoryInfo();
  free(data );
  data = malloc(3); /* 3 bytes*/
  printf("After  Malloc 2");
  printMemoryInfo();
  free(data );
  data = malloc(6); /* 6 bytes*/
  printf("After  Malloc 3");
  printMemoryInfo();
  free(data );
  data = malloc(10); /* 10 bytes*/
  printf("After  Malloc 4");
  printMemoryInfo();
  free(data );

}

Initial
Heap Blocks = 99128
After  Malloc 1
Heap Blocks = 99144
After  Malloc 2
Heap Blocks = 99144
After  Malloc 3
Heap Blocks = 99160
After  Malloc 4
Heap Blocks = 99160

From the Above print log I am not able to match how much its getting allocated first time for 1 bytes , it increases by 16 and will be same even if I allocate 2 or 3 , if I allocate 6 bytes it will increase by 32 and it will be same even for 10 bytes allocation.

I need to help understand mallinfo , I am working on 32 bit embedded processor.


Solution

  • There are two things going on here:

    1. malloc needs some space to store the meta-information about the length of memory block allocated. Often it's stored right before the block returned and takes 4 bytes.

    2. malloc always return an address that is aligned to the maximum alignment requirements for any kind of variable for the platform. Typically, that is 16-byte or 8-byte alignment. From malloc(3) man-page:

    The malloc() and calloc() functions return a pointer to the allocated memory, which is suitably aligned for any built-in type.