Hello,
I use a MKL17Z256 Kinetis MCU and I have a problem with a code with dynamic allocation.
All is OK when I use this code :
typedef struct
{
unsigned char Test_U8;
unsigned short Test_U16;
}test_str;
test_str Test_STR;
test_str * PointeurTest_STR = &Test_STR;
PointeurTest_STR->Test_U8 = 0;
PointeurTest_STR->Test_U16 = 0;
But MCU buggs when I use this one:
typedef struct
{
unsigned char Test_U8;
unsigned short Test_U16;
}test_str;
test_str* Test_STR = malloc(sizeof(test_str));
Test_STR->Test_U8 = 0;
Test_STR->Test_U16 = 0;
The problem is the MCU fall in defaultISR in startup:MKL.....S file
DefaultISR:
ldr r0, =DefaultISR
bx r0
What can cause this problem ?
已解决! 转到解答。
Check the compiler/link options. Replace -Os with -O2 if you are using GCC.
The L family does not deal with unaligned accesses and the 'Small' model saves space by not aligning things.
This can make the code look like random faults as things are moved around. Sometimes things end up aligned by accident and it will work.
Indirectly related it, in a structure it is better to put things from the largest to the smallest, that is reverse the unsigned char and unsigned short (better to use <stdint.h> types actually) in the test structure. Placing things from small to big can waste a lot of memory due to hidden structure alignment bytes. There are compiler options to pack the structures.
Also check the linker script to see how much heap space is allocated. Some of the default ones allocate no heap space and the stack collides with things leading to faults.
Perhaps this is why it looks like the heap is at zero in the IDE.
Check the compiler/link options. Replace -Os with -O2 if you are using GCC.
The L family does not deal with unaligned accesses and the 'Small' model saves space by not aligning things.
This can make the code look like random faults as things are moved around. Sometimes things end up aligned by accident and it will work.
Indirectly related it, in a structure it is better to put things from the largest to the smallest, that is reverse the unsigned char and unsigned short (better to use <stdint.h> types actually) in the test structure. Placing things from small to big can waste a lot of memory due to hidden structure alignment bytes. There are compiler options to pack the structures.
Also check the linker script to see how much heap space is allocated. Some of the default ones allocate no heap space and the stack collides with things leading to faults.
Perhaps this is why it looks like the heap is at zero in the IDE.
It wasn't on -Os but -O0, but I changed it to -O2.
I saw Heap Size was at 0x0000 and Heap Stack was at 0x0400. So I changed heap size to 0x0400 and it works well. I just saw in another post that change this heap size resolved the problem. Effectively it works.
I noted your advise about structure configuration.
Thank you,
Sam