1 /*-------------------------------------------------------------------------
2 realloc.c - reallocate allocated memory.
4 Copyright (C) 2004 - Maarten Brock, sourceforge.brock@dse.nl
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with this library; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 -------------------------------------------------------------------------*/
25 #if defined(SDCC_STACK_AUTO) || defined(SDCC_z80) || defined(SDCC_gbz80)
26 #define CRITICAL critical
31 //--------------------------------------------------------------------
32 //realloc function implementation for embedded system
33 //Non-ANSI keywords are C51 specific.
34 // xdata - variable in external memory (just RAM)
35 //--------------------------------------------------------------------
37 #if _SDCC_MALLOC_TYPE_MLH
41 typedef struct _MEMHEADER MEMHEADER;
51 #define HEADER_SIZE (sizeof(MEMHEADER)-sizeof(char))
52 #define MEM(x) (&x->mem)
56 #define HEADER_SIZE sizeof(MEMHEADER)
57 #define MEM(x) (x->mem)
61 extern MEMHEADER xdata * _sdcc_prev_memheader;
63 // apart from finding the header
64 // this function also finds it's predecessor
65 extern MEMHEADER xdata * _sdcc_find_memheader(void xdata * p);
67 void xdata * realloc (void * p, size_t size)
69 register MEMHEADER xdata * pthis;
70 register MEMHEADER xdata * pnew;
71 register void xdata * ret;
75 pthis = _sdcc_find_memheader(p);
78 if (size > (0xFFFF-HEADER_SIZE))
80 ret = (void xdata *) NULL; //To prevent overflow in next line
84 size += HEADER_SIZE; //We need a memory for header too
86 if ((((unsigned int)pthis->next) - ((unsigned int)pthis)) >= size)
87 {//if spare is more than needed
93 if ((_sdcc_prev_memheader) &&
94 ((((unsigned int)pthis->next) -
95 ((unsigned int)_sdcc_prev_memheader) -
96 _sdcc_prev_memheader->len) >= size))
98 pnew = (MEMHEADER xdata * )((char xdata *)_sdcc_prev_memheader + _sdcc_prev_memheader->len);
99 _sdcc_prev_memheader->next = pnew;
100 memmove(pnew, pthis, pthis->len);
106 ret = malloc(size - HEADER_SIZE);
109 memcpy(ret, MEM(pthis), pthis->len - HEADER_SIZE);