[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.6 - (view) (download)

1 : Isibaar 1.2 #include <stdlib.h>
2 :     #include <stdio.h>
3 :     #include "mem_align.h"
4 :    
5 : edgomez 1.6 void *
6 :     xvid_malloc(size_t size,
7 :     uint8_t alignment)
8 : Isibaar 1.2 {
9 : edgomez 1.3 uint8_t *mem_ptr;
10 : edgomez 1.6
11 :     if (!alignment) {
12 : edgomez 1.4
13 :     /* We have not to satisfy any alignment */
14 : edgomez 1.6 if ((mem_ptr = (uint8_t *) malloc(size + 1)) != NULL) {
15 : edgomez 1.4
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.6 } else {
25 : edgomez 1.3 uint8_t *tmp;
26 : edgomez 1.6
27 : edgomez 1.4 /*
28 :     * Allocate the required size memory + alignment so we
29 :     * can realign the data if necessary
30 :     */
31 :    
32 : edgomez 1.6 if ((tmp = (uint8_t *) malloc(size + alignment)) != NULL) {
33 : edgomez 1.4
34 :     /* Align the tmp pointer */
35 : edgomez 1.6 mem_ptr =
36 :     (uint8_t *) ((uint32_t) (tmp + alignment - 1) &
37 :     (~(uint32_t) (alignment - 1)));
38 : edgomez 1.4
39 :     /*
40 :     * Special case where malloc have already satisfied the alignment
41 :     * We must add alignment to mem_ptr because we must store
42 :     * (mem_ptr - tmp) in *(mem_ptr-1)
43 :     * If we do not add alignment to mem_ptr then *(mem_ptr-1) points
44 :     * to a forbidden memory space
45 :     */
46 : edgomez 1.6 if (mem_ptr == tmp)
47 :     mem_ptr += alignment;
48 : edgomez 1.4
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.6 *(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 : edgomez 1.6 void
66 :     xvid_free(void *mem_ptr)
67 : Isibaar 1.2 {
68 :    
69 : edgomez 1.4 /* *(mem_ptr - 1) give us the offset to the real malloc block */
70 : edgomez 1.6 if (mem_ptr)
71 :     free((uint8_t *) mem_ptr - *((uint8_t *) mem_ptr - 1));
72 : Isibaar 1.2
73 :     }

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