embeddedartistry / libmemory

Embedded systems memory management library. Implementations for malloc(), free(), and other useful memory management functions
https://embeddedartistry.com
MIT License
216 stars 44 forks source link

Add alignment block splitting to malloc_freelist #91

Open michaeljclark opened 6 months ago

michaeljclark commented 6 months ago

Description

The main allocator is modified to split blocks to align them, returning surplus to the free list.

I am sharing this because I think this approach is a little cleaner than the existing approach. It has several advantages and adds minimal complexity. It has been tested locally but it needs more testing and review. The primary code path should be unchanged for regular allocations besides dropping the minimum allocation size and calculating _alignmentslack which should always be zero for regular allocations.

The fundamental algorithm is mostly unchanged although there is additional logic to calculate _alignmentslack in the case that the alignment is greater than the alignment of the found block. If _alignmentslack is non-zero it is used to split the block so that block is sufficiently aligned with the surplus returned to the free list. Some indent has been removed for readability.

_alignedfree is now redundant but it is kept for compatibility. It is no longer necessary to unwrap an offset field in wrapper headers as the main allocation header block is aligned and free can be called directly on aligned allocations, so _alignedfree now simply delegates to free(). Also, the surplus memory to align blocks is not wasted and can be allocated.

This changes needs rigorous testing and review. This is a heads up!

Type of change

How Has This Been Tested?

Test Configuration:

Checklist:

phillipjohnston commented 6 months ago

Thanks for the PR! I am traveling this week, and I will give it a detailed look when I returned.

michaeljclark commented 6 months ago

Thanks! It's mostly just a heads up. Take your time...

It hadn't occurred to me but perhaps you indented code on the bodies of if conditions as a secure coding practice because if-not-clause-or-not-clause with an early return could be more prone to logic errors than an if-and-clause-and-clause with an indented block. In any case it should not be too hard to change the indentation if you prefer it the other way.

michaeljclark commented 3 days ago

curious if you had a chance to look at this PR more closely.