Skip to content

Commit e8910f6

Browse files
Nicolas Pitrenashif
authored andcommitted
lib/os/heap: document the reason behind the header field ordering
This is not obvious why the order is important when only looking at the header file. Signed-off-by: Nicolas Pitre <[email protected]>
1 parent a617083 commit e8910f6

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

lib/os/heap.h

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,26 +33,31 @@
3333
* field accessors since we can't use natural syntax.
3434
*
3535
* The fields are:
36-
* SIZE_AND_USED: the total size (including header) of the chunk in
37-
* 8-byte units. The bottom bit stores a "used" flag.
3836
* LEFT_SIZE: The size of the left (next lower chunk in memory)
3937
* neighbor chunk.
38+
* SIZE_AND_USED: the total size (including header) of the chunk in
39+
* 8-byte units. The bottom bit stores a "used" flag.
4040
* FREE_PREV: Chunk ID of the previous node in a free list.
4141
* FREE_NEXT: Chunk ID of the next node in a free list.
4242
*
4343
* The free lists are circular lists, one for each power-of-two size
4444
* category. The free list pointers exist only for free chunks,
4545
* obviously. This memory is part of the user's buffer when
4646
* allocated.
47+
*
48+
* The field order is so that allocated buffers are immediately bounded
49+
* by SIZE_AND_USED of the current chunk at the bottom, and LEFT_SIZE of
50+
* the following chunk at the top. This ordering allows for quick buffer
51+
* overflow detection by testing left_chunk(c + chunk_size(c)) == c.
4752
*/
4853
typedef size_t chunkid_t;
4954

55+
enum chunk_fields { LEFT_SIZE, SIZE_AND_USED, FREE_PREV, FREE_NEXT };
56+
5057
#define CHUNK_UNIT 8U
5158

5259
typedef struct { char bytes[CHUNK_UNIT]; } chunk_unit_t;
5360

54-
enum chunk_fields { LEFT_SIZE, SIZE_AND_USED, FREE_PREV, FREE_NEXT };
55-
5661
struct z_heap_bucket {
5762
chunkid_t next;
5863
};

0 commit comments

Comments
 (0)