3 * @author aurelien.morelle@parrot.fr
7 #include <VP_Os/vp_os_malloc.h>
18 vp_os_calloc(size_t nmemb, size_t size)
21 void *res = calloc(nmemb, size);
25 return calloc(nmemb, size);
26 #endif // <- DEBUG_MODE
30 vp_os_malloc(size_t size)
33 void *res = malloc(size);
38 #endif // <- DEBUG_MODE
42 vp_os_malloc_no_assert(size_t size)
55 #endif // <- DEBUG_MODE
58 // align_size has to be a power of two !!!
60 // The basic working of this algorithm is to allocate a bigger chunk of data than requested.
61 // This chunk of data must be big enough to contain an address aligned on requested boundary
62 // We also alloc 2 more words to keep base ptr (bptr) & requested size (size) of allocation
63 // bptr is the base pointer of this allocation
64 // _____ ______ ______ __________
65 // ... | bptr | size | .... |
66 // _____|______|______|__________|
68 void* vp_os_aligned_malloc(size_t size, size_t align_size)
70 char *ptr, *aligned_ptr;
73 size_t align_mask = align_size - 1;
75 // Check if align_size is a power of two
76 // If the result of this test is non zero then align_size is not a power of two
77 if( align_size & align_mask )
80 // Allocation size is :
81 // - Requested user size
82 // - a size (align_size) to make sure we can align on the requested boundary
83 // - 8 more bytes to register base adress & allocation size
84 allocation_size = size + align_size + 2*sizeof(int);
86 ptr = (char*) vp_os_malloc(allocation_size);
90 ptr2 = (int*)(ptr + 2*sizeof(int));
91 aligned_ptr = ptr + 2*sizeof(int) + (align_size - ((size_t) ptr2 & align_mask));
93 ptr2 = (int*)(aligned_ptr - 2*sizeof(int));
94 *ptr2++ = (int) (aligned_ptr - ptr);
100 void vp_os_aligned_free(void *ptr)
102 int* ptr2 = (int*)ptr - 2;
104 vp_os_free( ((char*)ptr - *ptr2) );
108 vp_os_aligned_realloc(void* ptr, size_t size, size_t align_size)
117 vp_os_aligned_free(ptr);
123 int* ptr2 = (int*)ptr - 1;
130 ptr_ret = vp_os_aligned_malloc(size, align_size);
132 // Compute smallest size
133 if( size > old_size )
139 vp_os_memcpy( ptr_ret, aligned_ptr, size );
141 vp_os_free( ((char*)ptr - *ptr2) );
145 ptr_ret = vp_os_aligned_malloc(size, align_size);
153 vp_os_realloc(void *ptr, size_t size)
156 void *res = realloc(ptr, size);
159 #else // ! DEBUG_MODE
160 return realloc(ptr, size);
161 #endif // <- DEBUG_MODE