garray: Allow over-allocation in g_array_insert_vals()

Previously, g_array_insert_vals() would crash if called with an index
off the end of the array. This is inconsistent with the behaviour of
other methods (like g_array_set_size()), which will expand the array as
necessary.

Modify g_array_insert_vals() to expand the array as necessary. New array
elements will be cleared to zero if the GArray was constructed with
(clear_ == TRUE).

Signed-off-by: Philip Withnall <withnall@endlessm.com>

https://bugzilla.gnome.org/show_bug.cgi?id=795975
This commit is contained in:
Philip Withnall 2018-05-09 15:35:23 +01:00
parent 3eeec77800
commit 89f45e96b2

View File

@ -506,6 +506,11 @@ g_array_prepend_vals (GArray *farray,
* *
* Inserts @len elements into a #GArray at the given index. * Inserts @len elements into a #GArray at the given index.
* *
* If @index_ is greater than the arrays current length, the array is expanded.
* The elements between the old end of the array and the newly inserted elements
* will be initialised to zero if the array was configured to clear elements;
* otherwise their values will be undefined.
*
* @data may be %NULL if (and only if) @len is zero. If @len is zero, this * @data may be %NULL if (and only if) @len is zero. If @len is zero, this
* function is a no-op. * function is a no-op.
* *
@ -538,6 +543,11 @@ g_array_insert_vals (GArray *farray,
if (len == 0) if (len == 0)
return farray; return farray;
/* Is the index off the end of the array, and hence do we need to over-allocate
* and clear some elements? */
if (index_ >= array->len)
return g_array_append_vals (g_array_set_size (farray, index_), data, len);
g_array_maybe_expand (array, len); g_array_maybe_expand (array, len);
memmove (g_array_elt_pos (array, len + index_), memmove (g_array_elt_pos (array, len + index_),