Skip to content

Commit 84fd57c

Browse files
committed
Fix missing alignment in calloc() and realloc()
The calloc() and realloc() implementations did not align the requested size before passing it to the allocator. This could result in returning non-aligned memory blocks, which may trigger unaligned memory access exceptions on RISC-V. Align the total size in calloc() and the input size in realloc() to ensure the allocator always returns properly aligned memory.
1 parent 877f973 commit 84fd57c

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

lib/malloc.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ void *calloc(uint32_t nmemb, uint32_t size)
211211
if (unlikely(nmemb && size > MALLOC_MAX_SIZE / nmemb))
212212
return NULL;
213213

214-
uint32_t total_size = nmemb * size;
214+
uint32_t total_size = ALIGN4(nmemb * size);
215215
void *buf = malloc(total_size);
216216

217217
if (buf)
@@ -234,6 +234,8 @@ void *realloc(void *ptr, uint32_t size)
234234
return NULL;
235235
}
236236

237+
size = ALIGN4(size);
238+
237239
memblock_t *old_block = ((memblock_t *) ptr) - 1;
238240

239241
/* Validate the existing block */

0 commit comments

Comments
 (0)