Handmade Hero»Forums»Code
Brendon
2 posts
Why "Block + 1" in AcquireAssetMemory on Day 160?
Why isn't it just "Block", why the extra "+ 1"? Isn't Block the thing you want to return?

Here is some of the relevant the code from handmade_asset.cpp:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
internal void *
AcquireAssetMemory(game_assets *Assets, memory_index Size)
{
    void *Result = 0;

    for(;;)
    {
        asset_memory_block *Block = FindBlockForSize(Assets, Size);
        if(Block)
        {
            Block->Flags |= AssetMemory_Used;
            
            Assert(Size <= Block->Size);
            Result = (u8 *)(Block + 1);

            memory_index RemainingSize = Block->Size - Size;
            memory_index BlockSplitThreshold = 4096; // TODO(casey): Set this based on the smallest asset?
            if(RemainingSize > BlockSplitThreshold)
            {
                Block->Size -= RemainingSize;
                InsertBlock(Block, RemainingSize, (u8 *)Result + Size);
            }
            else
            {
                // TODO(casey): Actually record the unused portion of the memory
                // in a block so that we can do the merge on blocks when neighbors
                // are freed.
            }
            
            break;
Mattie
35 posts
Why "Block + 1" in AcquireAssetMemory on Day 160?
Block is actually just the header for the following free space, not the free space itself. "Block + 1" points to the memory location immediately following Block, which is where the actual free space starts.
Mārtiņš Možeiko
2559 posts / 2 projects
Why "Block + 1" in AcquireAssetMemory on Day 160?
If I remember correctly then that is because asset_memory_block is stored in memroy just before the actual asset data. Here's a diagram:

1
2
3
4
5
6
+-----------------------+-------------+
|   asset_memory_block  |  asset data |
+-----------------------+-------------+
^                       ^
|                       |
+--- Block pointer      +-- Result pointer


Block + 1 is simply way how to get pointer to actual asset data. Doing + 1 for pointer is same as adding sizeof(type) to it's address in bytes.
Bryan Taylor
55 posts
Why "Block + 1" in AcquireAssetMemory on Day 160?
"Block" points to the header struct for the block -- which we use to track the size for freeing later. The actual memory we're allocating follows directly *after* the block header. "Block + 1" increments the pointer by the size of the header, giving us a pointer to the memory itself.
Brendon
2 posts
Why "Block + 1" in AcquireAssetMemory on Day 160?
Thanks, I guess I missed the brackets. I thought he was incrementing it by 1 u8, not 1 asset_memory_block, that makes mush more sense.