1 /* extendbuf.c -- manage a dynamically-allocated buffer
3 Copyright 2004, 2010 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program 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
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 /* Written by James Yougnman <jay@gnu.org>. */
29 #include "extendbuf.h"
32 /* We initially use a small default size to ensure that this code
36 # define SIZE_DEFAULT 16
40 decide_size (size_t current, size_t wanted)
45 newsize = SIZE_DEFAULT;
49 while (newsize < wanted)
51 if (2 * newsize < newsize)
60 extendbuf (void* existing, size_t wanted, size_t *allocated)
64 void *result; /* leave uninitialised to allow static code checkers to identify bugs */
69 newsize = decide_size (*allocated, wanted);
71 if ( (*allocated) == 0 )
73 /* Sanity check: If there is no existing allocation size, there
74 * must be no existing allocated buffer.
76 assert (NULL == existing);
78 (*allocated) = newsize;
79 result = malloc (newsize);
83 if (newsize != (*allocated) )
85 (*allocated) = newsize;
86 result = realloc (existing, newsize);
100 /* malloc () or realloc () may have changed errno, but in the
101 success case we want to preserve the previous value.
110 xextendbuf (void* existing, size_t wanted, size_t *allocated)
112 void *p = extendbuf (existing, wanted, allocated);