Useful aligned malloc function

Discuss the development of new homebrew software, tools and libraries.

Moderators: cheriff, TyRaNiD

Post Reply
jboldiga
Posts: 27
Joined: Mon Jun 20, 2005 10:16 am

Useful aligned malloc function

Post by jboldiga »

Here is a useful aligned malloc function you can use for when dynamically allocating vertex data for 3D stuff. Enjoy.

Example use:

Code: Select all

typedef struct Vertex
{
	float u, v;
	float x, y, z;
}Vertex;

Vertex* vertices;
int  numVerts = 36;

// 16 byte aligned memory block
vertices = aligned_malloc(numVerts * sizeof(Vertex), 16);
And here is the source:

Code: Select all

// returns a block of memory aligned to "alignSize" bytes
void* aligned_malloc(size_t size, size_t alignSize) 
{
	void**	ptr;
	void**	alignedPtr;

	ptr = (void*)malloc(size + alignSize + sizeof(void*));
	
	if(ptr == NULL) 
		return(NULL);

	alignedPtr			= (void**)((int)(ptr) & 0xfffffff0);
	*alignedPtr++	    = ptr;

	return(alignedPtr);
}

// frees an aligned block of memory
void aligned_free(void* ptr) 
{
	void* ptr2 = *((void**)ptr - 1);
	free(ptr2);
}
ooPo
Site Admin
Posts: 2023
Joined: Sat Jan 17, 2004 9:56 am
Location: Canada
Contact:

Post by ooPo »

Why not just use memalign()?
jboldiga
Posts: 27
Joined: Mon Jun 20, 2005 10:16 am

Post by jboldiga »

cuz didnt know there was a memalign in libc :)
ooPo
Site Admin
Posts: 2023
Joined: Sat Jan 17, 2004 9:56 am
Location: Canada
Contact:

Post by ooPo »

Well, at least you learned something about malloc in the process. :)
User avatar
Jim
Posts: 476
Joined: Sat Jul 02, 2005 10:06 pm
Location: Sydney
Contact:

Post by Jim »

Code: Select all

ptr = (void*)malloc(size + alignSize + sizeof(void*)); 
alignedPtr         = (void**)((int)(ptr) & 0xfffffff0);
*alignedPtr++       = ptr;
ooh, nasty bug :-p
Use memalign :-)

Jim
Post Reply