Вопрос

What happens when g_array_append_val() or one of the other append/prepend functions in GLib, makes the length of the GArray larger than what guint (unsigned int) can hold?

The documentation doesn't say anything about it, so should I assume that I have to check this myself before appending (unless I know that the list will never grow beyond 65535 elements)?

Это было полезно?

Решение

GArray is defined as following:

struct GArray {
  gchar *data;
  guint len;
};

So it can contain as many data as memory can hold. And, guint is unsigned int, which can be up to 4Gb, not 65536.

Digging deeper to GLib source, you can see, that g_array_append_val will call g_array_expand, which will later rely on g_realloc to reallocate memory. And in g_realloc sources you can see:

newmem = glib_mem_vtable.realloc (mem, n_bytes);
TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
if (newmem)
  return newmem;

g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes", G_STRLOC, n_bytes);

So it will fail with message 'failed to allocate %d bytes'.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top