I checked it it works !!
#include <stdio.h>
#include <stdlib.h>
/*************************************************
Name :- aligned_malloc
Arguments:- number of bytes & Alignment Boundry
Return :- NULL on error
valid pointer on success
Working :- It will allocate memory with starting address
multiple of alignment passed and returns pointer
to it on success.
Ex.
aligned_malloc(50,128);
This will allocate 50 bytes of memory with
starting address multiple of 128.
*************************************************/
void *aligned_malloc(size_t bytes, size_t alignment)
{
void *p1 ,*p2; // basic pointer needed for computation.
if((p1 =(void *) malloc(bytes + alignment + sizeof(size_t)))==NULL)
return NULL;
size_t addr=(size_t)p1+alignment+sizeof(size_t);
p2=(void *)(addr - (addr%alignment));
*((size_t *)p2-1)=(size_t)p1;
return p2;
}
/************************************************
Name :- aligned_free
Arguments :- pointer to be freed
Returns :- Nothing
*************************************************/
void aligned_free(void *p )
{
free((void *)(*((size_t *) p-1)));
}
#include <stdio.h>
#include <stdlib.h>
/*************************************************
Name :- aligned_malloc
Arguments:- number of bytes & Alignment Boundry
Return :- NULL on error
valid pointer on success
Working :- It will allocate memory with starting address
multiple of alignment passed and returns pointer
to it on success.
Ex.
aligned_malloc(50,128);
This will allocate 50 bytes of memory with
starting address multiple of 128.
*************************************************/
void *aligned_malloc(size_t bytes, size_t alignment)
{
void *p1 ,*p2; // basic pointer needed for computation.
if((p1 =(void *) malloc(bytes + alignment + sizeof(size_t)))==NULL)
return NULL;
size_t addr=(size_t)p1+alignment+sizeof(size_t);
p2=(void *)(addr - (addr%alignment));
*((size_t *)p2-1)=(size_t)p1;
return p2;
}
/************************************************
Name :- aligned_free
Arguments :- pointer to be freed
Returns :- Nothing
*************************************************/
void aligned_free(void *p )
{
free((void *)(*((size_t *) p-1)));
}
memalign函数可以直接实现这个功能,限制是alignment必须是2的power
没有评论:
发表评论