Added cycle gadget test section. The 'Radio' tab has been renamed to
[AROS.git] / compiler / stdc / realloc.c
blob1e8d2c2989143ff101abf63a16e6f29e958a8f63
1 /*
2 Copyright © 1995-2012, The AROS Development Team. All rights reserved.
3 $Id$
5 C99 function realloc().
6 */
8 #include <aros/cpu.h>
9 #include <proto/exec.h>
11 /*****************************************************************************
13 NAME */
14 #include <stdlib.h>
16 void * realloc (
18 /* SYNOPSIS */
19 void * oldmem,
20 size_t size)
22 /* FUNCTION
23 Change the size of an allocated part of memory. The memory must
24 have been allocated by malloc() or calloc(). If you reduce the
25 size, the old contents will be lost. If you enlarge the size,
26 the new contents will be undefined.
28 INPUTS
29 oldmem - What you got from malloc() or calloc().
30 size - The new size.
32 RESULT
33 A pointer to the allocated memory or NULL. If you don't need the
34 memory anymore, you can pass this pointer to free(). If you don't,
35 the memory will be freed for you when the application exits.
37 NOTES
38 If you get NULL, the memory at oldmem will not have been freed and
39 can still be used.
41 EXAMPLE
43 BUGS
45 SEE ALSO
46 calloc(), free(), malloc()
48 INTERNALS
50 ******************************************************************************/
52 UBYTE * mem, * newmem;
53 size_t oldsize;
55 if (!oldmem)
56 return malloc (size);
58 mem = (UBYTE *)oldmem - AROS_ALIGN(sizeof(size_t));
59 oldsize = *((size_t *)mem);
61 /* Reduce or enlarge the memory ? */
62 if (size < oldsize)
64 /* Don't change anything for small changes */
65 if ((oldsize - size) < 4096)
66 newmem = oldmem;
67 else
68 goto copy;
70 else if (size == oldsize) /* Keep the size ? */
71 newmem = oldmem;
72 else
74 copy:
75 newmem = malloc (size);
77 if (newmem)
79 if (size > oldsize)
80 size = oldsize;
81 CopyMem (oldmem, newmem, size);
82 free (oldmem);
86 return newmem;
87 } /* realloc */