| View previous topic :: View next topic |
| Author |
Message |
jboldiga
Joined: 20 Jun 2005 Posts: 27
|
Posted: Tue Jul 19, 2005 10:01 am Post subject: Useful aligned malloc function |
|
|
Here is a useful aligned malloc function you can use for when dynamically allocating vertex data for 3D stuff. Enjoy.
Example use:
| Code: |
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: |
// 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);
}
|
|
|
| Back to top |
|
 |
ooPo Site Admin
Joined: 17 Jan 2004 Posts: 2032 Location: Canada
|
Posted: Tue Jul 19, 2005 10:59 am Post subject: |
|
|
| Why not just use memalign()? |
|
| Back to top |
|
 |
jboldiga
Joined: 20 Jun 2005 Posts: 27
|
Posted: Tue Jul 19, 2005 11:19 am Post subject: |
|
|
| cuz didnt know there was a memalign in libc :) |
|
| Back to top |
|
 |
ooPo Site Admin
Joined: 17 Jan 2004 Posts: 2032 Location: Canada
|
Posted: Tue Jul 19, 2005 12:12 pm Post subject: |
|
|
| Well, at least you learned something about malloc in the process. :) |
|
| Back to top |
|
 |
Jim

Joined: 02 Jul 2005 Posts: 487 Location: Sydney
|
Posted: Tue Jul 19, 2005 6:29 pm Post subject: |
|
|
| Code: |
ptr = (void*)malloc(size + alignSize + sizeof(void*));
alignedPtr = (void**)((int)(ptr) & 0xfffffff0);
*alignedPtr++ = ptr; |
ooh, nasty bug :-p
Use memalign :-)
Jim _________________ http://www.dbfinteractive.com |
|
| Back to top |
|
 |
|