solidc
Robust collection of general-purpose cross-platform C libraries and data structures designed for rapid and safe development in C
Loading...
Searching...
No Matches
aligned_alloc.h
Go to the documentation of this file.
1
6#ifndef ALIGNED_ALLOC_H
7#define ALIGNED_ALLOC_H
8
9#include <stdlib.h>
10
11#ifdef __cplusplus
12extern "C" {
13#endif
14
15#if defined(_WIN32) || defined(__CYGWIN__)
16#include <malloc.h> // _aligned_malloc and _aligned_free
17#endif
18
19// Cross-platform aligned memory allocation
20static inline void* aligned_alloc_xp(size_t alignment, size_t size) {
21 // Alignment must be a power of two and at least sizeof(void*)
22 if ((alignment & (alignment - 1)) != 0 || alignment < sizeof(void*)) {
23 return NULL;
24 }
25
26#if defined(_WIN32) || defined(__CYGWIN__)
27 return _aligned_malloc(size, alignment);
28#else
29
30// Use standard C11 aligned_alloc where available
31#if __STDC_VERSION__ >= 201112L
32 return aligned_alloc(alignment, size);
33#else
34 // Fallback for older C standards
35 void* ptr = NULL;
36 if (posix_memalign(&ptr, alignment, size) != 0) {
37 return NULL;
38 }
39 return ptr;
40#endif
41#endif
42}
43
44// Cross-platform aligned memory deallocation
45static inline void aligned_free_xp(void* ptr) {
46#if defined(_WIN32) || defined(__CYGWIN__)
47 _aligned_free(ptr);
48#else
49 free(ptr);
50#endif
51}
52
53#define ALIGNED_ALLOC(alignment, size) aligned_alloc_xp(alignment, size)
54#define ALIGNED_FREE(ptr) aligned_free_xp(ptr)
55
56#ifdef __cplusplus
57}
58#endif
59
60#endif // ALIGNED_ALLOC_H