add rt_realloc_align for posix_memalign

This commit is contained in:
2024-02-20 10:47:24 +08:00
parent 03971211ef
commit 780291d5b0
3 changed files with 66 additions and 5 deletions

View File

@ -37,9 +37,9 @@ void *malloc(size_t n)
{
#ifdef RT_USING_HEAP
#ifndef RT_USING_POSIX_MEMALIGN
return rt_malloc(n);
return rt_malloc(n);
#else
return rt_malloc_align(n, RT_ALIGN_SIZE);
return rt_malloc_align(n, RT_ALIGN_SIZE);
#endif
#else
_NO_HEAP_ERROR();
@ -51,7 +51,11 @@ RTM_EXPORT(malloc);
void *realloc(void *rmem, size_t newsize)
{
#ifdef RT_USING_HEAP
return rt_realloc(rmem, newsize);
#ifndef RT_USING_POSIX_MEMALIGN
return rt_realloc(rmem, newsize);
#else
return rt_realloc_align(rmem, newsize, RT_ALIGN_SIZE);
#endif
#else
_NO_HEAP_ERROR();
return RT_NULL;
@ -74,9 +78,9 @@ void free(void *rmem)
{
#ifdef RT_USING_HEAP
#ifndef RT_USING_POSIX_MEMALIGN
rt_free(rmem);
rt_free(rmem);
#else
rt_free_align(rmem);
rt_free_align(rmem);
#endif
#else
_NO_HEAP_ERROR();

View File

@ -268,6 +268,7 @@ void rt_free(void *ptr);
void *rt_realloc(void *ptr, rt_size_t nbytes);
void *rt_calloc(rt_size_t count, rt_size_t size);
void *rt_malloc_align(rt_size_t size, rt_size_t align);
void *rt_realloc_align(void *rmem, rt_size_t newsize, rt_size_t align);
void rt_free_align(void *ptr);
void rt_memory_info(rt_size_t *total,

View File

@ -1698,6 +1698,62 @@ RT_WEAK void *rt_malloc_align(rt_size_t size, rt_size_t align)
}
RTM_EXPORT(rt_malloc_align);
/**
* This function will change the size of previously allocated memory block,
* which address is aligned to the specified alignment size.
*
* @param rmem is the pointer to memory allocated by rt_malloc_align.
*
* @param newsize is the required new size.
*
* @param align is the alignment size.
*
* @return the changed memory block address.
*/
RT_WEAK void *rt_realloc_align(void *rmem, size_t newsize, rt_size_t align)
{
void *real_ptr;
void *ptr;
void *align_ptr;
int uintptr_size;
rt_size_t align_size;
/* sizeof pointer */
uintptr_size = sizeof(void*);
uintptr_size -= 1;
/* align the alignment size to uintptr size byte */
align = ((align + uintptr_size) & ~uintptr_size);
/* get total aligned size */
align_size = ((newsize + uintptr_size) & ~uintptr_size) + align;
real_ptr = (void *) * (rt_ubase_t *)((rt_ubase_t)rmem - sizeof(void *));
ptr = rt_realloc(real_ptr, align_size);
if (ptr != RT_NULL)
{
/* the allocated memory block is aligned */
if (((rt_ubase_t)ptr & (align - 1)) == 0)
{
align_ptr = (void *)((rt_ubase_t)ptr + align);
}
else
{
align_ptr = (void *)(((rt_ubase_t)ptr + (align - 1)) & ~(align - 1));
}
/* set the pointer before alignment pointer to the real pointer */
*((rt_ubase_t *)((rt_ubase_t)align_ptr - sizeof(void *))) = (rt_ubase_t)ptr;
ptr = align_ptr;
}
return ptr;
}
/**
* This function release the memory block, which is allocated by
* rt_malloc_align function and address is aligned.