This article explains by example how heap works.
Memory allocation refers to allocation of pieces of memory pools belonging to a large memory space called heap. Some space of heap may be unused so we can locate the allocated pools there.
There are cases where we don't know the exact size of an array from the begining, we don't know if the array is small or big.
For example, as in this article, we will make multiplication tables of integers. Sending an integer to the microcontroller via ASC0 (with the help of Hyperterminal, no keyboard is present) like 4 we take:
The multiplication table of 4 is:
1 2 3 4
--------------
1| 1 2 3 4
2| 2 4 6 8
3| 3 6 9 12
4| 4 8 12 16
It is obvious that the size of this array depends on the value of the integer that we send to the microcontroller and we can't know it from the begining. Program during execution must save enough memory space for the array, "on the fly".
The solution is malloc() function. Malloc returns a pointer to a free heap memory space allocating the memory pool whoose size determined previously initializing it usung the init_mempool function, so we can save data to a free memory space at heap.. We use it here as :
ptr_int = malloc(max * max * sizeof(unsigned int));
max is an integer, say 9, that we sent via ASC0 and sizeof(unsigned int) is the size of the unsigned integer number of the compiler, 2 bytes. So the total number of bytes that will be allocated is 9*9*2=162.
We asked an unsigned integer memory pool space of 200 places (400 bytes) to be allocated, so the maximum number that the program accepts is 14 (14*14*2=382 bytes in allocation). Sending 15 we are over the memory pool size determined with init_mempool and malloc() fails.
Don't forget to free, after use, the allocated memory pool with free().
The heap example c code.
Heap functions
The result |