utils: Add malloc/free wrappers returning aligned data

While we could use posix_memalign(3), that is not fully portable. Further, it
might be difficult on some platforms to properly catch it in leak-detective,
which results in invalid free()s when releasing such memory.

We instead use a simple wrapper, which allocates larger data, and saves the
padding size in the allocated header. This requires that memory is released
using a dedicated function.

To reduce the risk of invalid free() when working on corrupted data, we fill up
all the padding with the padding length, and verify it during free_align().
This commit is contained in:
Martin Willi
2015-04-15 13:44:40 +02:00
parent edab6c658c
commit f206bb7444
3 changed files with 101 additions and 0 deletions
+18
View File
@@ -566,6 +566,24 @@ typedef struct timespec timespec_t;
*/
typedef struct sockaddr sockaddr_t;
/**
* malloc(), but returns aligned memory.
*
* The returned pointer must be freed using free_align(), not free().
*
* @param size size of allocated data
* @param align alignment, up to 255 bytes, usually a power of 2
* @return allocated hunk, aligned to align bytes
*/
void* malloc_align(size_t size, u_int8_t align);
/**
* Free a hunk allocated by malloc_align().
*
* @param ptr hunk to free
*/
void free_align(void *ptr);
/**
* Same as memcpy, but XORs src into dst instead of copy
*/