Portable aligned memory allocation

This commit is contained in:
Eric Biggers 2015-01-22 20:49:57 -06:00
parent 7b955dadc7
commit c3e397e661
4 changed files with 55 additions and 2 deletions

View File

@ -58,6 +58,8 @@ if(SUPPORT_GZIP)
endif()
endif()
set(LIB_SOURCES ${LIB_SOURCES} src/aligned_malloc.c)
option(SUPPORT_NEAR_OPTIMAL_PARSING "Support near optimal parsing (high compression mode)" ON)
if(SUPPORT_NEAR_OPTIMAL_PARSING)
add_definitions(-DSUPPORT_NEAR_OPTIMAL_PARSING=1)

36
src/aligned_malloc.c Normal file
View File

@ -0,0 +1,36 @@
/*
* aligned_malloc.c
*
* Aligned memory allocation using only malloc() and free().
* Avoids portability problems with posix_memalign(), aligned_alloc(), etc.
*
* This file has no copyright assigned and is placed in the Public Domain.
*/
#include "aligned_malloc.h"
#include <stdint.h>
#include <stdlib.h>
void *
aligned_malloc(size_t alignment, size_t size)
{
const uintptr_t mask = alignment - 1;
char *ptr = NULL;
char *raw_ptr;
raw_ptr = malloc(mask + sizeof(size_t) + size);
if (raw_ptr) {
ptr = (char *)raw_ptr + sizeof(size_t);
ptr = (void *)(((uintptr_t)ptr + mask) & ~mask);
*((size_t *)ptr - 1) = ptr - raw_ptr;
}
return ptr;
}
void
aligned_free(void *ptr)
{
if (ptr)
free((char *)ptr - *((size_t *)ptr - 1));
}

14
src/aligned_malloc.h Normal file
View File

@ -0,0 +1,14 @@
/*
* aligned_malloc.c
*
* Aligned memory allocation.
*
* This file has no copyright assigned and is placed in the Public Domain.
*/
#pragma once
#include <stddef.h>
extern void *aligned_malloc(size_t alignment, size_t size);
extern void aligned_free(void *ptr);

View File

@ -10,6 +10,7 @@
#include "libdeflate.h"
#include "aligned_malloc.h"
#include "deflate_compress.h"
#include "deflate_constants.h"
#include "unaligned.h"
@ -2197,7 +2198,7 @@ deflate_alloc_compressor(unsigned int compression_level)
#endif
size = offsetof(struct deflate_compressor, nonoptimal_end);
c = aligned_alloc(MATCHFINDER_ALIGNMENT, size);
c = aligned_malloc(MATCHFINDER_ALIGNMENT, size);
if (!c)
return NULL;
@ -2313,7 +2314,7 @@ deflate_compress(struct deflate_compressor *c,
LIBEXPORT void
deflate_free_compressor(struct deflate_compressor *c)
{
free(c);
aligned_free(c);
}
unsigned int