Skip to content

Commit

Permalink
Protect API from double free
Browse files Browse the repository at this point in the history
  • Loading branch information
xoofx committed Jul 5, 2024
1 parent 3e6a2ff commit a184a99
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/XenoAtom.Allocators.Tests/BasicTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ public async Task TestAllocate3()

// Free allocation 1
tlsf.Free(allocation1);
Assert.ThrowsException<ArgumentException>(() => tlsf.Free(allocation1));

Assert.AreEqual(2U, tlsf.Chunks[0].UsedBlockCount);
Assert.AreEqual(2U, tlsf.Chunks[0].FreeBlockCount);

Expand Down
9 changes: 8 additions & 1 deletion src/XenoAtom.Allocators/TlsfAllocator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,15 @@ public TlsfAllocation Allocate(uint size)
public void Free(TlsfAllocation allocation)
{
int blockIndex = (int)allocation.BlockIndex;
if ((uint)blockIndex >= (uint)_blockCount)
{
throw new ArgumentException($"The block index {blockIndex} is out of range", nameof(allocation));
}
ref var block = ref GetBlockAt(blockIndex);
Debug.Assert(block.IsUsed);
if (!block.IsUsed)
{
throw new ArgumentException($"The block at index {blockIndex} is already free", nameof(allocation));
}
block.IsUsed = false;

// Update statistics for the chunk
Expand Down

0 comments on commit a184a99

Please sign in to comment.