Add overflow protection to g_string_maybe_expand()

This commit is contained in:
Sebastian Dröge 2021-11-25 14:19:53 +02:00
parent d01dc6d23a
commit b5447e8e35

View File

@ -76,9 +76,17 @@ static void
g_string_maybe_expand (GString *string,
gsize len)
{
/* Detect potential overflow */
if G_UNLIKELY ((G_MAXSIZE - string->len - 1) < len)
g_error ("adding %" G_GSIZE_FORMAT " to string would overflow", len);
if (string->len + len >= string->allocated_len)
{
string->allocated_len = g_nearest_pow (string->len + len + 1);
/* If the new size is bigger than G_MAXSIZE / 2, only allocate enough
* memory for this string and don't over-allocate. */
if (string->allocated_len == 0)
string->allocated_len = string->len + len + 1;
string->str = g_realloc (string->str, string->allocated_len);
}
}