1 /*
2     libfame - Fast Assembly MPEG Encoder Library
3     Copyright (C) 2000-2001 Damien Vincent
4 
5     This library is free software; you can redistribute it and/or
6     modify it under the terms of the GNU Library General Public
7     License as published by the Free Software Foundation; either
8     version 2 of the License, or (at your option) any later version.
9 
10     This library is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13     Library General Public License for more details.
14 
15     You should have received a copy of the GNU Library General Public
16     License along with this library; if not, write to the Free
17     Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19 /**************************** malloc wrapper for alignment ***********************************/
20 
21 #define ALIGN 32
22 
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <inttypes.h>
26 
fame_malloc(size_t size)27 void* fame_malloc(size_t size)
28 {
29   unsigned char *ptr, *aligned, *padding;
30 
31   /* Struture of fame_alloc :
32    * -> byte0     = padding[0]                             --> ptr
33    * -> ...
34    * -> byte(n-1) = padding[n-1]
35    * -> byten     = n                                      --> padding
36    * -> byte(n+1) = first element of the array (aligned)   --> aligned
37    * -> ...
38    */
39 
40   ptr = (unsigned char*) malloc(size+ALIGN);
41   if (ptr == NULL) {
42 	perror("fame_malloc");
43 	exit(1);
44   }
45   aligned = (unsigned char*) (((uintptr_t)ptr & (~(ALIGN-1))) + ALIGN );
46   padding = aligned - 1;
47   *padding = (ALIGN-1) - ((uintptr_t)ptr & (ALIGN-1));
48 
49   return ((void*)aligned);
50 }
51 
52 
53 
fame_free(void * aligned)54 void fame_free(void* aligned)
55 {
56   unsigned char *ptr, *padding;
57 
58   /* Use char* arithmetic, as void* arithm. is illecal in ANSI C. */
59   padding = ((unsigned char*)aligned) - 1;
60   ptr  = padding - (*padding);
61 
62   free(ptr);
63 }
64