I have been tinkering around with this program but i am still unable to understand it. This is supposed to allocate memory returned my malloc and align it to a 4 byte boundary. I got this from the net but i have a lot of questions about it.
[insert]Any insights why those things have been done would be appreciated.Code:#include <stdio.h>
#include <stdlib.h>
/* align_size has to be a power of two !! */
void *aligned_malloc(size_t size, size_t align_size) {
char *ptr,*ptr2,*aligned_ptr;
int align_mask = align_size - 1; // what is this for and why i am subtracting -1 from it.
ptr=(char *)malloc(size + align_size + sizeof(int)); // i allocate 72 bytes though i want only 4 bytes
if(ptr==NULL) return(NULL);
ptr2 = ptr + sizeof(int); // why adding sizeof(int) to it aligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask)); // this one goes above my head
ptr2 = aligned_ptr - sizeof(int); // why??????
*((int *)ptr2)=(int)(aligned_ptr - ptr); // for what reason ?????
return(aligned_ptr);
}
void aligned_free(void *ptr) {
int *ptr2=(int *)ptr - 1;
ptr = (int *)ptr - *ptr2;
free(ptr);
}
int main( void )
{
// declare the type of data pointer that
// we want to allocate...
char* pData = 0;
pData = aligned_malloc( 64, 4 ); // let's get 64 bytes aligned on a 4-byte boundry
if( pData != NULL )
{
; // do something with our allocated memory
// free it...
aligned_free( pData );
pData = 0;
}
return 0;
}