Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure pointer is 8-byte aligned in stack_alloc::alloc #3014

Merged
merged 4 commits into from
Jan 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions stan/math/memory/stack_alloc.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,9 @@ class stack_alloc {
* Return a newly allocated block of memory of the appropriate
* size managed by the stack allocator.
*
* The allocated pointer will be 8-byte aligned.
* The allocated pointer will be 8-byte aligned. If the number
* of bytes requested is not a multiple of 8, the reserved space
* will be padded up to the next multiple of 8.
*
* This function may call C++'s <code>malloc()</code> function,
* with any exceptions percolated through this function.
Expand All @@ -167,9 +169,11 @@ class stack_alloc {
* @return A pointer to the allocated memory.
*/
inline void* alloc(size_t len) {
size_t pad = len % 8 == 0 ? 0 : 8 - len % 8;

// Typically, just return and increment the next location.
char* result = next_loc_;
next_loc_ += len;
next_loc_ += len + pad;
// Occasionally, we have to switch blocks.
if (unlikely(next_loc_ >= cur_block_end_)) {
result = move_to_next_block(len);
Expand Down
15 changes: 14 additions & 1 deletion test/unit/math/memory/stack_alloc_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,15 @@ TEST(stack_alloc, alloc) {
allocator.recover_all();
}

TEST(stack_alloc, alloc_aligned) {
stan::math::stack_alloc allocator;
int* x = allocator.alloc_array<int>(3);

double* y = allocator.alloc_array<double>(4);
EXPECT_TRUE(stan::math::is_aligned(y, 8));
allocator.recover_all();
}

TEST(stack_alloc, in_stack) {
stan::math::stack_alloc allocator;

Expand All @@ -113,7 +122,11 @@ TEST(stack_alloc, in_stack_second_block) {
char* y = allocator.alloc_array<char>(1);
EXPECT_TRUE(allocator.in_stack(x));
EXPECT_TRUE(allocator.in_stack(y));
EXPECT_FALSE(allocator.in_stack(y + 1));
// effect of padding
EXPECT_TRUE(allocator.in_stack(y + 1));
EXPECT_TRUE(allocator.in_stack(y + 7));

EXPECT_FALSE(allocator.in_stack(y + 8));

allocator.recover_all();
EXPECT_FALSE(allocator.in_stack(x));
Expand Down
Loading