When allocating a memory block from the heap memory, a 4-byte magic number is automatically written before and after the allocated memory block.
Top guard Memory block Tail guard A5 : A5 : A5 : A5 AA : AA : AA : AA
You can have the heap memory checked by checking if this magic number is corrupted. To have this check done, enable one of the following zones in the Debug zone.
ZONE_HEAP_CHK
-
When this zone is enabled, when the free function or realloc function is called, it checks the magic numbers before and after the memory block specified by the parameter. If they are corrupted, the following log message will be output.
Example log message when Tail guard is corrupted:
[HEAP] #### Tail guard is corrupted! #### [HEAP] #### 00 aa aa aa [HEAP] #### Allocated by 0x5000ba9 [HEAP] #### Size = 16 [HEAP] #### Handle = 0x861086c
- The magic number has been changed to 00: AA: AA: AA.
- This memory is allocated by the program at address 0x5000ba9 and is 16 bytes in size.
- Address of the memory block is 0x861086c.
void main(void) { char *p = malloc(16); *(p+16) = 0; free(p); while(1) { Idle(); } }
Example log message when Top guard is corrupted:
[HEAP] #### Top guard is corrupted! (0x00a5a5a5) #### [HEAP] #### Allocated by 0x5000ba9 [HEAP] #### Size = 16 [HEAP] #### Handle = 0x861086c
- The magic number has been changed to A5: A5: A5: 00.
- This memory is allocated by the program at address 0x5000ba9 and is 16 bytes in size.
- Address of the memory block is 0x861086c.
void main(void) { char *p = malloc(16); *(p-1) = 0; free(p); while(1) { Idle(); } }
ZONE_HEAP_LOG
-
When this zone is enabled, in addition to the ZONE_HEAP_CHK functions, log messages similar to the following example are automatically output when the malloc, calloc, realloc, or free function is called.
[HEAP]+malloc(16) at 5000ba9 [HEAP]-malloc(16) -> 0x861086c n=4 at 5000ba9 [HEAP]+free(0x861086c) at 5000bba [HEAP]-free(0x861086c) n=3 at 5000bba
- The malloc function was called from the program at address 0x5000ba9 with the parameter value of 16.
- The memory at address 0x861086c was allocated and the total number of memory blocks became 4.
- The free function was called from the program at address 0x5000bba, and the total number of memory blocks became 3.
ZONE_HEAP_ALL
- When this zone is enabled, in addition to the ZONE_HEAP_LOG functions, when the malloc, calloc, realloc or free function is called, the magic numbers of all currently allocated memory blocks are checked.
If they are corrupted, the above log message will be output.
Please note that enabling ZONE_HEAP_ALL has a large overhead.
Limitations:
- If the total number of allocated memory blocks is 8192 or less, the inspection function described in this section will work.
- If more than 8192 memory blocks are allocated, the memory allocation itself will continue to operate, but after that, the inspection function described in this section will stop operating until the device is restarted.
See also
Last updated: 2021/05/31