cancel
Showing results for 
Search instead for 
Did you mean: 

Calling rand() on Cortex-M3 produces hard fault due to malloc() error (SOLVED).

Zanon.Luciano
Senior

Very strange behavior, the instruction:

uint32_t xid;

xid = rand();

cause hard fault due to unaligned address.

I am using Atollic TrueSTUDIO Version: 9.3.0 

15 REPLIES 15
Uwe Bonnes
Principal II

Maybe you run M3 code on a M0? Maybe the rand() implementation that TrueSTUDIO uses is broken?

Zanon.Luciano
Senior

This problem occurs on M3 and also on M0, and seems related to the configuration of the project because on some projects it works without problems and on others it doesn't.

I just don't understand why and I still can't give more precise indications ...

TDK
Guru

Most likely the rand() library you're using is not meant for your processor instruction set.

You should step into the rand() code to find the offending instruction. It's possible rand() is fine and the hardfault is from an interrupt.

If you feel a post has answered your question, please click "Accept as Solution".
Zanon.Luciano
Senior

Hello TDK, the library is that of atollic and cannot be an interrupt problem because moving rand () at any point of the program, always crashes during execution of the rand () instruction.

But my program places the stack (0x400 bytes) at 0x20000400 (by myprogram.ld file) and in this situation rand () generates the crash in the statement str r2, [r0, # 16] (where r2 = 1).

If I move the stack to the top of memory then rand () works correctly !!!!!

This is crazy ...

Anyone have any ideas?

It sounds like you could be overflowing the stack. Increase the size. Does the r0 register have a valid memory address?
If you feel a post has answered your question, please click "Accept as Solution".
Zanon.Luciano
Senior

R0 contains 0 (invalid address) and this causes the crash.

It's not a stack size issue because this also happens with the larger stack and also after the crash the stack area is still clean.

I'm continuing the tests ....

By the way, with the keil compiler everything works fine ...

TDK
Guru

Interesting. Might be hard to debug without knowing what rand() is doing. Good luck. Keil is probably using a different implementation of rand().

If you feel a post has answered your question, please click "Accept as Solution".

In mixed disasm/source view, the the offending instruction to respective source line. It's often straightforward to see, which variable maps to which register. Here, I'd say, you have a zero pointer, which was created elsewhere - maybe failed unchecked malloc()? - and just coincidentally happened to fault in rand().

JW

Zanon.Luciano
Senior

Hi JW it seems you're right, the first call to malloc () inside rand () returns R0 = 0 and then the crash ...

Do you have any idea why malloc () fails?