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

No. Inadequately set heap size?

I don't use IAR, and I consider unrestricted use of dynamic memory allocation in microcontrollers to be a methodology failure.

JW

Zanon.Luciano
Senior

I'm going crazy, ........... The heap is ok and i am working in Atollic environment.

Is it possible that having the stack at the bottom of the ram and the heap in a higher region could cause a malloc protection error?

And if so, what is the way to disable this protection?

I found the MALLOC_CHECK_ variable that could work but I don't know how to use it in an atollic environment ....

Zanon.Luciano
Senior

The problem is solved !!

As mentioned, the problem was that in my environment the stack is located in a ram area at a lower address than the heap.

Normally the heap is growing and the stack is decreasing so the check that is done is to avoid the collision between the heap and the stack, this check is done in the "_sbrk" routine in syscalls.c.

It was enough to modify the _sbrk routine (which is available at the user level) and test the area following the heap instead of the stack pointer to solve the problem !!

Luciano

Zanon.Luciano
Senior

As always, in the end the problem was a simple thing, but as always at the beginning it seemed a big problem ...

Piranha
Chief II

You could be interested in reading this article by @Dave Nadler​:

http://www.nadler.com/embedded/newlibAndFreeRTOS.html

Ultimately the best option for devices and operating systems without MMU is to not use any heap memory at all, because it can easily lead to heap fragmentation and failure.

Zanon.Luciano
Senior

thanks Piranha I will read it carefully!:smiling_face_with_smiling_eyes: