[cvs] / xvidcore / src / utils / mem_align.c Repository:
ViewVC logotype

Annotation of /xvidcore/src/utils/mem_align.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.4 - (view) (download)

1 : Isibaar 1.2 #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 : edgomez 1.3 uint8_t *mem_ptr;
8 : Isibaar 1.2
9 : edgomez 1.4 if(!alignment)
10 : edgomez 1.3 {
11 : edgomez 1.4
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 : edgomez 1.3 *mem_ptr = 0;
18 : edgomez 1.4
19 :     /* Return the mem_ptr pointer */
20 : edgomez 1.3 return (void *) mem_ptr++;
21 : edgomez 1.4
22 : edgomez 1.3 }
23 : edgomez 1.4
24 : edgomez 1.3 }
25 :     else
26 :     {
27 :     uint8_t *tmp;
28 : Isibaar 1.2
29 : edgomez 1.4 /*
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 : edgomez 1.3 mem_ptr = (uint8_t *)((uint32_t)(tmp + alignment - 1)&(~(uint32_t)(alignment - 1)));
39 : edgomez 1.4
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 : edgomez 1.3 *(mem_ptr - 1) = (uint8_t)(mem_ptr - tmp);
54 : edgomez 1.4
55 :     /* Return the aligned pointer */
56 : edgomez 1.3 return (void *) mem_ptr;
57 : edgomez 1.4
58 : edgomez 1.3 }
59 :     }
60 :    
61 :     return NULL;
62 : Isibaar 1.2
63 :     }
64 :    
65 :     void xvid_free(void *mem_ptr)
66 :     {
67 :    
68 : edgomez 1.4 /* *(mem_ptr - 1) give us the offset to the real malloc block */
69 :     free((uint8_t*)mem_ptr - *((uint8_t*)mem_ptr - 1));
70 : Isibaar 1.2
71 :     }

No admin address has been configured
ViewVC Help
Powered by ViewVC 1.0.4