This article explains by example how realloc function works.
In article 12 you learned about the need of existence of malloc function. But what is happening if during the execution of the program we need more RAM storage space whose size we can't know from the beging? the solution is realloc().
In summary: we initialize a memory pool giving its size, then malloc() and realloc() find an unused or if you want a free RAM storage place returning a pointer to it, so we can begin the allocation process storing data in it. Unused or free RAM space does not means that this space is initialized to zero surely. But we, may be, don't worry about it. Else we use calloc().
Free() function freezes the memory pool from the process of allocation.
At this example code that is a modification of code of article 12 we send an integer max to the microcontoller via ASC0 asking for a printf of its multiplication table .But during execution the program must take a decision: If number max is smaller than 10 then we want to prinrf and the multiplication table of (max+1) number. But if max is equal or greater than 10 then we want to printf and the multiplication table of (max-1) number .It is obvious that we need more free space for allocation, not known at the begining but finding it " on the fly " . So, the program returns two pointers for allocation:
We asked a memory pool for allocation of 400*2= 800 bytes. So the maximun number that the program accepts is 15, (max-1=14), we have 15*15*2+14*14*2=792 bytes for allocation.
If realloc() fails then nptr_int==NULL . You have to reset the program.
Important note: In C examples you will see a cast (it is permitted here because malloc() returns a void * pointer) of the returning from malloc() pointer like (unsigned int *) malloc(...) to be sure that the returned pointer points to unsigned integers.
A pointer to a character (1 byte long object) has to "walk" 1 byte to find the next character inside of the memory space but a pointer to an integer ( 2 bytes long object) has to "walk" 2 bytes to find the next integer.
So, always remember: A pointer to a character is entirely different than a pointer to an integer, than a pointer to a float etc. There is not a "clever" compiler to protect you!
Take the C code.
Of course , as and for the other examples, you can use the simulator (do the right settings first) using the serial window #1. Try it.
Exercise 1: Change the memory pool size and play with malloc and realloc failurs.
Exercise 2: Repeat the program using calloc instead of malloc.
So, this is the end of ... heap.