6 |
{ |
{ |
7 |
uint8_t *mem_ptr; |
uint8_t *mem_ptr; |
8 |
|
|
9 |
if(alignment == 0) |
if(!alignment) |
10 |
{ |
{ |
11 |
if((mem_ptr = (uint8_t *) malloc(size + 1)) != NULL) { |
|
12 |
|
/* We have not to satisfy any alignment */ |
13 |
|
if((mem_ptr = (uint8_t *) malloc(size + 1)) != NULL) |
14 |
|
{ |
15 |
|
|
16 |
|
/* Store (mem_ptr - "real allocated memory") in *(mem_ptr-1) */ |
17 |
*mem_ptr = 0; |
*mem_ptr = 0; |
18 |
|
|
19 |
|
/* Return the mem_ptr pointer */ |
20 |
return (void *) mem_ptr++; |
return (void *) mem_ptr++; |
21 |
|
|
22 |
} |
} |
23 |
|
|
24 |
} |
} |
25 |
else |
else |
26 |
{ |
{ |
27 |
uint8_t *tmp; |
uint8_t *tmp; |
28 |
|
|
29 |
if((tmp = (uint8_t *) malloc(size + alignment)) != NULL) { |
/* |
30 |
|
* Allocate the required size memory + alignment so we |
31 |
|
* can realign the data if necessary |
32 |
|
*/ |
33 |
|
|
34 |
|
if((tmp = (uint8_t *) malloc(size + alignment)) != NULL) |
35 |
|
{ |
36 |
|
|
37 |
|
/* Align the tmp pointer */ |
38 |
mem_ptr = (uint8_t *)((uint32_t)(tmp + alignment - 1)&(~(uint32_t)(alignment - 1))); |
mem_ptr = (uint8_t *)((uint32_t)(tmp + alignment - 1)&(~(uint32_t)(alignment - 1))); |
39 |
|
|
40 |
|
/* |
41 |
|
* Special case where malloc have already satisfied the alignment |
42 |
|
* We must add alignment to mem_ptr because we must store |
43 |
|
* (mem_ptr - tmp) in *(mem_ptr-1) |
44 |
|
* If we do not add alignment to mem_ptr then *(mem_ptr-1) points |
45 |
|
* to a forbidden memory space |
46 |
|
*/ |
47 |
|
if(mem_ptr == tmp) mem_ptr += alignment; |
48 |
|
|
49 |
|
/* |
50 |
|
* (mem_ptr - tmp) is stored in *(mem_ptr-1) so we are able to retrieve |
51 |
|
* the real malloc block allocated and free it in xvid_free |
52 |
|
*/ |
53 |
*(mem_ptr - 1) = (uint8_t)(mem_ptr - tmp); |
*(mem_ptr - 1) = (uint8_t)(mem_ptr - tmp); |
54 |
|
|
55 |
|
/* Return the aligned pointer */ |
56 |
return (void *) mem_ptr; |
return (void *) mem_ptr; |
57 |
|
|
58 |
} |
} |
59 |
} |
} |
60 |
|
|
65 |
void xvid_free(void *mem_ptr) |
void xvid_free(void *mem_ptr) |
66 |
{ |
{ |
67 |
|
|
68 |
uint8_t *real_ptr; |
/* *(mem_ptr - 1) give us the offset to the real malloc block */ |
69 |
|
free((uint8_t*)mem_ptr - *((uint8_t*)mem_ptr - 1)); |
|
real_ptr = (uint8_t*)mem_ptr; |
|
|
|
|
|
free(real_ptr - *(real_ptr -1)); |
|
70 |
|
|
71 |
} |
} |