Skip to content

Commit 3b46954

Browse files
Fix misaligned pointer returned in heap allocator
Signed-off-by: Aravind Gopalakrishnan <[email protected]>
1 parent 52b1d92 commit 3b46954

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

shared/source/utilities/heap_allocator.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,10 @@ class HeapAllocator {
192192

193193
auto ptr = freedChunks[bestFitIndex].ptr + sizeDelta;
194194
freedChunks[bestFitIndex].size = sizeDelta;
195+
196+
if (!isAligned(ptr, requiredAlignment)) {
197+
return 0llu;
198+
}
195199
return ptr;
196200
}
197201
}

shared/test/unit_test/utilities/heap_allocator_tests.cpp

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (C) 2018-2021 Intel Corporation
2+
* Copyright (C) 2018-2022 Intel Corporation
33
*
44
* SPDX-License-Identifier: MIT
55
*
@@ -174,6 +174,31 @@ TEST(HeapAllocatorTest, GivenOnlyMoreThanTwiceBiggerSizeChunksInFreedChunksWhenG
174174
EXPECT_EQ(deltaSize, freedChunks[2].size);
175175
}
176176

177+
TEST(HeapAllocatorTest, GivenMoreThanTwiceBiggerSizeChunksInFreedChunksWhenGetIsCalledAndAlignmentDoesNotThenNullIsReturned) {
178+
uint64_t ptrBase = 0x100000llu;
179+
size_t size = 1024 * 4096;
180+
auto pLowerBound = ptrBase;
181+
182+
auto allocAlign = 8162u;
183+
184+
auto heapAllocator = std::make_unique<HeapAllocatorUnderTest>(ptrBase, size, allocationAlignment, sizeThreshold);
185+
186+
std::vector<HeapChunk> freedChunks;
187+
uint64_t ptrExpected = 0llu;
188+
size_t requestedSize = 2 * 4096;
189+
190+
freedChunks.emplace_back(pLowerBound, 9 * 4096);
191+
pLowerBound += 9 * 4096;
192+
freedChunks.emplace_back(pLowerBound, 3 * 4096);
193+
194+
EXPECT_EQ(2u, freedChunks.size());
195+
196+
auto ptrReturned = heapAllocator->getFromFreedChunks(requestedSize, freedChunks, allocAlign);
197+
198+
EXPECT_EQ(ptrExpected, ptrReturned);
199+
EXPECT_EQ(2u, freedChunks.size());
200+
}
201+
177202
TEST(HeapAllocatorTest, GivenStoredChunkAdjacentToLeftBoundaryOfIncomingChunkWhenStoreIsCalledThenChunkIsMerged) {
178203
uint64_t ptrBase = 0x100000llu;
179204
size_t size = 1024 * 4096;

0 commit comments

Comments
 (0)