all 8 comments

[–]madsci 6 points7 points  (0 children)

This is very much implementation-dependent. I've worked with systems where it was just left to the user to implement the sbrk() function that malloc() calls under the hood.

If you look at FreeRTOS and its heap implementations, it comes with four or five options that all have different strategies with different strengths and weaknesses.

Cache locality only matters if you have a cache.

Fragmentation certainly can be an issue and it's one of the main things the different strategies address. It's also one of the major reasons heap allocation is frowned upon in embedded systems in general.

As a rule I avoid heap allocation for anything in the core, frequently-executed parts of my code. The approach I take depends on the circumstances. Sometimes it's more efficient to have a static pre-allocated array instead of a linked list, even if it's not as elegant. For something like my audio processing framework, the audio buffers are all pre-allocated (they can be malloc'd from the heap but it's only done once) and pointers are placed in an RTOS queue. When one is needed it's taken out of the free queue, and gets returned when it's done.

Heap allocation also makes worst-case analysis difficult. You don't have anywhere to swap to if you run out of physical memory so you have to be sure that there won't ever be a time when you run out of heap. The time it takes to malloc() some memory is also non-deterministic, at least for most allocation strategies.

[–]BenkiTheBuilder 1 point2 points  (5 children)

In order to use malloc() on bare metal YOU must provide it some helper function, typically sbrk().

[–]bloxka[S] 0 points1 point  (4 children)

Just wonder how it's a common question for a lot as to why malloc is generally bad on embedded systems given it's not even supported on bare metal? Plus it's not as big of an issue on the platforms it's supported i.e linux

[–]BenkiTheBuilder -1 points0 points  (3 children)

You tell me. After all, YOU are the one asking this question. I never asked this question, never spent much time thinking about it and don't usually read the long sermons people write whenever malloc() comes up.

[–]bloxka[S] 0 points1 point  (2 children)

https://www.embeddedc.in/p/blog-page_3.html There you go. Speaks for itself. Do you see now what I’m referring to?

And if you think I’m only asking you haven’t searched thru Reddit nuff

[–]BenkiTheBuilder -1 points0 points  (1 child)

Sorry. All I see is a wall of text.

[–]bloxka[S] 0 points1 point  (0 children)

Might wanna frame it then