NetBurner 3.5.0
PDF Version
 
malloc

This example demonstrates the usage of malloc and free. It identifies way's to track heap space usage by calling spaceleft() and mallinfo(), which can help prevent an applications from running out of dynamic memory.

It is important to use both spaceleft() and mallinfo() to determine the size of the heap. As this application demonstrates, spaceleft() alone will not always give the total space available to malloc.

Dynamic memory and fragmentation is beyond the scope of this example, but in short, the largest amount of contiguous dynamic memory an application can malloc depends on how the application handles malloc and free. For example:

  • A heap has a total of 1MB of memory available.
  • The application allocates 100KB 3 times, lets call them A, B and C.
  • There is now 700KB left. Functions spaceleft() and mallinfo() will report this number.
  • The spaceleft() function always reports the amount of "untouched" memory. This is memory that has never been allocated, and does not include the amount available to the application that has been allocated and freed. It is useful in that it provides the application with the amount of contiguous dynamic memory that can be allocated. It is commonly referred to as a "watermark".
  • The mallinfo() function returns the total amount of heap space available, including both untouched and freed memory. So at this point in this 1MB example, it would report 700KB a well.
  • Now the application frees A and B. The spaceleft() function will report the watermark value of 700KB. The mallinfo() function will include the freed memory and report 900KB.

In this code example the application will allocate 3 chunks of space. The first is 1MB, then a 3MB, then a 512KB chunk. It will then free the data in a different order.

After every malloc and free, the amount of heap space will be displayed by both reporting functions showing heap space used, free, and untouched.