Why should I be carefull using the heap instead of the stack

Quite a lot of people have told me that I should be carefull when using the heap instead of the stack. I don't really get it, when I allocate memory in the heap, it occupies the same amount of memory then when I use the stack. Why should I use one more than the other?

Because memory allocation can fragment the heap and since many Arduinos don't have much RAM, it can happen more rapidly than you might expect.

1 Like

That is incorrect.

Allocating and deallocating space on the stack is automatic... the compiler generates the code so you don't have to. Allocating space on the heap is not so bad but it's easier to forget to deallocate the space and subsequently lose the handle. This creates wasted space and can badly fragment the heap, causing it to become unusable. If the functions that do this don't run frequently enough you'll have a tough time troubleshooting what will look like an intermittent problem.

Can you correct me? I was pretty sure about that?

There's some overhead memory requirements associated with the house keeping of dynamic allocation.

If you were to simply allocate heap memory and leave it allocated there's little risk or cost, but if that satisfies the programming requirement then there's no compelling reason to use the heap rather than fixed variable allocation.

The issue with heap allocation is when one deallocates heap memory and then goes to allocate a block of heap memory that does not fit in the same space as that deallocated so that additional memory must be used. Thus there are potentially unused holes in the whole of heap memory space, a situation known as heap fragmentation. Heap memory is blown if there is no contiguous free block of heap memory large enough to accomodate a newly allocated block even if the net available heap memory is larger than the block to be allocated.

Stack memory is allocated and deallocated at the border between allocated and unallocated stack memory. There are no unused holes in the allocation, so stack memory is blown only if a new allocation is larger than the net available free stack space.

One reason would be in implementing a library. Dynamic allocation in the library would enable the end user to make the tradeoff in memory usage between the application code and the library. Of course, it would be nice if the library gracefully handled the situation of being unable to allocate the requested memory by informing the application code ..... rather than just setting the stage for undefined behavior.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.