Vector 0.0.2
Loading...
Searching...
No Matches
aligned_alloc.c
1#include "vector.h"
2#include <stdlib.h>
3#include <stdio.h>
4#include <string.h>
5#include <assert.h>
6
7#define MAX_ALIGNMENT 2 * 1024 * 1024 // 4MB
8#define ALIGNED(bytes) &(alloc_t){.alignment = bytes}
9
10#if defined _WIN32 || defined __CYGWIN__
11#define aligned_alloc(alignment, size) _aligned_malloc(size, alignment)
12#endif
13
14// #ifdef __linux__
15// static_assert(0)
16// #endif
17
18typedef struct alloc
19{
20 size_t alignment;
21 size_t last_size;
22}
23alloc_t;
24
25int main(void)
26{
27 vector_t *aligned_vector = vector_create (
28 .element_size = sizeof(int),
30 .size = sizeof(alloc_t),
31 .data = ALIGNED(MAX_ALIGNMENT),
32 ),
33 );
34
35 assert((0 == (size_t)aligned_vector % MAX_ALIGNMENT)
36 && "Address must be aligned to MAX_ALIGNMENT");
37
38 // ...
39
40 vector_destroy(aligned_vector);
41 return 0;
42}
43
44void *vector_alloc(const size_t alloc_size, void *const param)
45{
46 assert(param);
47 alloc_t* alloc = (alloc_t*)param;
48 return aligned_alloc(alloc->alignment, alloc_size);
49}
50
51void *vector_realloc(void *const ptr, size_t alloc_size, void *const param)
52{
53 assert(ptr);
54 assert(alloc_size > 0);
55 assert(param);
56
57 alloc_t *alloc = (alloc_t*)param;
58
59 if (alloc_size == alloc->last_size)
60 {
61 return ptr;
62 }
63
64 void *new = aligned_alloc(alloc->alignment, alloc_size);
65 if (new)
66 {
67 memcpy(new, ptr, alloc->last_size);
68 alloc->last_size = alloc_size;
69 free(ptr);
70 }
71 return new;
72}
73
74void vector_free(void *const ptr, void *const param)
75{
76 (void) param;
77 free(ptr);
78}
79
void * vector_realloc(void *const ptr, size_t alloc_size, void *const param)
Reallocates already allocated memory chunk in order to change allocation size.
void * vector_alloc(const size_t alloc_size, void *const param)
Allocates memory chunk of alloc_size.
void vector_free(void *const ptr, void *const param)
Free allocation that was previously allocated.
#define vector_create(...)
Vector constructor.
Definition vector.h:162
#define alloc_opts(...)
Use this macro to define allocator opts in vector_opts_t.
Definition vector.h:153
void vector_destroy(vector_t *const vector)
Deallocates vector.
Definition vector.c:112
Vector control structure type.
Definition vector.c:24
Public interface of the vector.