Memory allocation thread and interrupt safety

nameofuser1
Posts: 6
Joined: Mon Oct 15, 2018 9:10 am

Memory allocation thread and interrupt safety

Postby nameofuser1 » Tue Dec 11, 2018 10:54 pm

Hi there!

Could anyone clarify for me please whether malloc/new are thread and interrupt safe? I can see that there is an implementation of _malloc_r in newlib directory which is considered to be thread safe. But what about common malloc? Regarding to the documentation it seems that malloc and _malloc_r wrap the same functions, however, I can not confirm that since I can not find malloc implementation anywhere. And what about new operator? Is it a simple wrapper about malloc as it used to be? Also I am not sure whether it is safe to call malloc/new inside an ISR.

Actually I do not like the idea of calling malloc inside interrupt handler, therefore I would like to write my own block memory allocator for allocating objects in ISR, however, I am not sure how to make it safe if interrupts are nested. Is portENTER_CRITICAL_ISR enough to prevent nesting?

ESP_Sprite
Posts: 9764
Joined: Thu Nov 26, 2015 4:08 am

Re: Memory allocation thread and interrupt safety

Postby ESP_Sprite » Wed Dec 12, 2018 3:18 am

They are threadsafe, but I would not assume they are interrupt-safe. I'm not sure why you would do a malloc in an ISR anyway, and even if it worked it does not sound like a good idea;l what's your use case there?

nameofuser1
Posts: 6
Joined: Mon Oct 15, 2018 9:10 am

Re: Memory allocation thread and interrupt safety

Postby nameofuser1 » Wed Dec 12, 2018 11:32 am

ESP_Sprite wrote:
Wed Dec 12, 2018 3:18 am
They are threadsafe, but I would not assume they are interrupt-safe. I'm not sure why you would do a malloc in an ISR anyway, and even if it worked it does not sound like a good idea;l what's your use case there?
Thanks for your reply! I allocate small event structures in order to avoid having huge tables or filling any table by means of c++ functionality. I do not like that idea too and as I said in original post I would like to switch to custom block allocator which will be very fast. However I am not sure how to prevent interrupt nesting.

ESP_Sprite
Posts: 9764
Joined: Thu Nov 26, 2015 4:08 am

Re: Memory allocation thread and interrupt safety

Postby ESP_Sprite » Thu Dec 13, 2018 6:05 am

Why not use an existing structure, like a FreeRTOS queue?

Who is online

Users browsing this forum: No registered users and 126 guests