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
59 vp_os_sfree(void **ptr)
66 #endif // <- DEBUG_MODE
70 // align_size has to be a power of two !!!
72 // The basic working of this algorithm is to allocate a bigger chunk of data than requested.
73 // This chunk of data must be big enough to contain an address aligned on requested boundary
74 // We also alloc 2 more words to keep base ptr (bptr) & requested size (size) of allocation
75 // bptr is the base pointer of this allocation
76 // _____ ______ ______ __________
77 // ... | bptr | size | .... |
78 // _____|______|______|__________|
80 void* vp_os_aligned_malloc(size_t size, size_t align_size)
82 char *ptr, *aligned_ptr;
85 size_t align_mask = align_size - 1;
87 // Check if align_size is a power of two
88 // If the result of this test is non zero then align_size is not a power of two
89 if( align_size & align_mask )
92 // Allocation size is :
93 // - Requested user size
94 // - a size (align_size) to make sure we can align on the requested boundary
95 // - 8 more bytes to register base adress & allocation size
96 allocation_size = size + align_size + 2*sizeof(int);
98 ptr = (char*) vp_os_malloc(allocation_size);
102 ptr2 = (int*)(ptr + 2*sizeof(int));
103 aligned_ptr = ptr + 2*sizeof(int) + (align_size - ((size_t) ptr2 & align_mask));
105 ptr2 = (int*)(aligned_ptr - 2*sizeof(int));
106 *ptr2++ = (int) (aligned_ptr - ptr);
112 void vp_os_aligned_free(void *ptr)
114 int* ptr2 = (int*)ptr - 2;
116 vp_os_free( ((char*)ptr - *ptr2) );
120 vp_os_aligned_realloc(void* ptr, size_t size, size_t align_size)
129 vp_os_aligned_free(ptr);
135 int* ptr2 = (int*)ptr - 1;
142 ptr_ret = vp_os_aligned_malloc(size, align_size);
144 // Compute smallest size
145 if( size > old_size )
151 vp_os_memcpy( ptr_ret, aligned_ptr, size );
153 vp_os_free( ((char*)ptr - *ptr2) );
157 ptr_ret = vp_os_aligned_malloc(size, align_size);
165 vp_os_realloc(void *ptr, size_t size)
168 void *res = realloc(ptr, size);
169 if (res==NULL) { perror(__FUNCTION__); }
172 #else // ! DEBUG_MODE
173 return realloc(ptr, size);
174 #endif // <- DEBUG_MODE