ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvs/xvidcore/src/utils/mem_align.c
Revision: 1.5
Committed: Sun Jun 9 11:23:13 2002 UTC (22 years, 4 months ago) by edgomez
Content type: text/plain
Branch: MAIN
Changes since 1.4: +2 -1 lines
Log Message:
Small change, avoid calling free with a random address

File Contents

# Content
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include "mem_align.h"
4
5 void *xvid_malloc(size_t size, uint8_t alignment)
6 {
7 uint8_t *mem_ptr;
8
9 if(!alignment)
10 {
11
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;
18
19 /* Return the mem_ptr pointer */
20 return (void *) mem_ptr++;
21
22 }
23
24 }
25 else
26 {
27 uint8_t *tmp;
28
29 /*
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)));
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);
54
55 /* Return the aligned pointer */
56 return (void *) mem_ptr;
57
58 }
59 }
60
61 return NULL;
62
63 }
64
65 void xvid_free(void *mem_ptr)
66 {
67
68 /* *(mem_ptr - 1) give us the offset to the real malloc block */
69 if(mem_ptr)
70 free((uint8_t*)mem_ptr - *((uint8_t*)mem_ptr - 1));
71
72 }