2 |
#include <stdio.h> |
#include <stdio.h> |
3 |
#include "mem_align.h" |
#include "mem_align.h" |
4 |
|
|
5 |
void *xvid_malloc(size_t size, uint8_t alignment) |
void * |
6 |
|
xvid_malloc(size_t size, |
7 |
|
uint8_t alignment) |
8 |
{ |
{ |
9 |
uint8_t *mem_ptr; |
uint8_t *mem_ptr; |
10 |
|
|
11 |
if(!alignment) |
if (!alignment) { |
|
{ |
|
12 |
|
|
13 |
/* We have not to satisfy any alignment */ |
/* We have not to satisfy any alignment */ |
14 |
if((mem_ptr = (uint8_t *) malloc(size + 1)) != NULL) |
if ((mem_ptr = (uint8_t *) malloc(size + 1)) != NULL) { |
|
{ |
|
15 |
|
|
16 |
/* Store (mem_ptr - "real allocated memory") in *(mem_ptr-1) */ |
/* Store (mem_ptr - "real allocated memory") in *(mem_ptr-1) */ |
17 |
*mem_ptr = 0; |
*mem_ptr = 0; |
21 |
|
|
22 |
} |
} |
23 |
|
|
24 |
} |
} else { |
|
else |
|
|
{ |
|
25 |
uint8_t *tmp; |
uint8_t *tmp; |
26 |
|
|
27 |
/* |
/* |
29 |
* can realign the data if necessary |
* can realign the data if necessary |
30 |
*/ |
*/ |
31 |
|
|
32 |
if((tmp = (uint8_t *) malloc(size + alignment)) != NULL) |
if ((tmp = (uint8_t *) malloc(size + alignment)) != NULL) { |
|
{ |
|
33 |
|
|
34 |
/* Align the tmp pointer */ |
/* Align the tmp pointer */ |
35 |
mem_ptr = (uint8_t *)((uint32_t)(tmp + alignment - 1)&(~(uint32_t)(alignment - 1))); |
mem_ptr = |
36 |
|
(uint8_t *) ((uint32_t) (tmp + alignment - 1) & |
37 |
|
(~(uint32_t) (alignment - 1))); |
38 |
|
|
39 |
/* |
/* |
40 |
* Special case where malloc have already satisfied the alignment |
* Special case where malloc have already satisfied the alignment |
43 |
* If we do not add alignment to mem_ptr then *(mem_ptr-1) points |
* If we do not add alignment to mem_ptr then *(mem_ptr-1) points |
44 |
* to a forbidden memory space |
* to a forbidden memory space |
45 |
*/ |
*/ |
46 |
if(mem_ptr == tmp) mem_ptr += alignment; |
if (mem_ptr == tmp) |
47 |
|
mem_ptr += alignment; |
48 |
|
|
49 |
/* |
/* |
50 |
* (mem_ptr - tmp) is stored in *(mem_ptr-1) so we are able to retrieve |
* (mem_ptr - tmp) is stored in *(mem_ptr-1) so we are able to retrieve |
62 |
|
|
63 |
} |
} |
64 |
|
|
65 |
void xvid_free(void *mem_ptr) |
void |
66 |
|
xvid_free(void *mem_ptr) |
67 |
{ |
{ |
68 |
|
|
69 |
/* *(mem_ptr - 1) give us the offset to the real malloc block */ |
/* *(mem_ptr - 1) give us the offset to the real malloc block */ |