gbytes: Return early if a NULL or 0-sized GBytes is created

In case data is NULL we ended up to call memcpy with NULL parameter
which is undefined behavior (see the trace below).

So instead of having multiple null checks to do just the same, simplify
the NULL or 0-sized cases.

../glib/gbytes.c:140:7: runtime error: null pointer passed as argument 2,
  which is declared to never be null
    #0 0x7f56ea7c667e in g_bytes_new ../glib/gbytes.c:140
    #1 0x5557c3659f06 in test_null ../glib/tests/bytes.c:453
    #2 0x7f56ea9c0f70 in test_case_run ../glib/gtestutils.c:3115
    #3 0x7f56ea9c0f70 in g_test_run_suite_internal ../glib/gtestutils.c:3210
    #4 0x7f56ea9c0ceb in g_test_run_suite_internal ../glib/gtestutils.c:3229
    #5 0x7f56ea9c1f89 in g_test_run_suite ../glib/gtestutils.c:3310
    #6 0x7f56ea9c20df in g_test_run ../glib/gtestutils.c:2379
    #7 0x5557c36599d2 in main ../glib/tests/bytes.c:536
This commit is contained in:
Marco Trevisan (Treviño) 2025-01-30 15:47:18 +01:00
parent 7ae8b1d132
commit d1b4f169a8

View File

@ -123,12 +123,15 @@ g_bytes_new (gconstpointer data,
{
g_return_val_if_fail (data != NULL || size == 0, NULL);
if (data == NULL || size == 0)
return g_bytes_new_with_free_func (NULL, size, NULL, NULL);
if (size <= G_BYTES_MAX_INLINE)
{
GBytesInline *bytes;
bytes = g_malloc (sizeof *bytes + size);
bytes->bytes.data = (data != NULL && size > 0) ? bytes->inline_data : NULL;
bytes->bytes.data = bytes->inline_data;
bytes->bytes.size = size;
bytes->bytes.free_func = NULL;
bytes->bytes.user_data = NULL;