1 /* extendbuf.c -- manage a dynamically-allocated buffer
3 Copyright 2004 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 2, or (at your option)
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, write to the Free Software Foundation,
17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
19 /* Written by James Yougnman <jay@gnu.org>. */
31 #include "extendbuf.h"
34 /* We initially use a small default size to ensure that this code
38 # define SIZE_DEFAULT 16
42 decide_size(size_t current
, size_t wanted
)
47 newsize
= SIZE_DEFAULT
;
51 while (newsize
< wanted
)
53 if (2 * newsize
< newsize
)
62 extendbuf(void* existing
, size_t wanted
, size_t *allocated
)
66 void *result
; /* leave uninitialised to allow static code checkers to identify bugs */
71 newsize
= decide_size(*allocated
, wanted
);
73 if ( (*allocated
) == 0 )
75 /* Sanity check: If there is no existing allocation size, there
76 * must be no existing allocated buffer.
78 assert(NULL
== existing
);
80 (*allocated
) = newsize
;
81 result
= xmalloc(newsize
);
85 if (newsize
!= (*allocated
) )
87 (*allocated
) = newsize
;
88 result
= xrealloc (existing
, newsize
);
99 /* xmalloc() or xrealloc() may have changed errno, but in the
100 success case we want to preserve the previous value.