cglib

memory leak by using g_log_structured


I would like to use Glib to achieve structured logging into the system journal of Linux (Ubuntu). Out of three possibilities, one regularly results in a memory access error.

Unfortunately, I found that using g_log_structured(..) regularly leads to a memory leak. Here the code:

#define G_LOG_USE_STRUCTURED
#define G_LOG_DOMAIN "MyDomain"

#include <glib.h>
#include <stdio.h>

int main(int argc, char *argv[]) 
{
   g_log_set_writer_func (g_log_writer_journald, NULL, NULL);

/*  regularly leads to a memory leak.
    g_log_structured (G_LOG_DOMAIN,
                   G_LOG_LEVEL_DEBUG,
                   "CODE_FILE", "mysource.c",
                   "CODE_LINE", 312,
                   "MESSSAGE_ID", "06d4df59e6c24647bfe69d2c27ef0b4e",
                   "MESSAGE", "You have %d eggs", 12 + 2);
*/

/* The following log message will go to journald */
        const GLogField fields[] = {
               {"MESSAGE", "This is the message", -1},
               {"EIGENES_FELD", "mysource.c", -1},
               {"STATUS", "3",-1},
        };

        // works        
        g_log_structured_array (G_LOG_LEVEL_DEBUG, fields,G_N_ELEMENTS (fields));
        
        // works
        GLogWriterOutput result = g_log_writer_journald (
                                 G_LOG_LEVEL_INFO,
                                 fields,
                                 G_N_ELEMENTS(fields),
                                 NULL); 
    return 0;
}

Unfortunately, I found that using g_log_structured(..) regularly leads to a memory leak.

Okt 19 14:44:05 holger kernel: a.out[12281]: segfault at 138 ip 00007fe6b6b7401d sp 00007ffe746157e8 error 4 in libc.so.6[7fe6b6a22000+178000] likely on CPU 1 (core 1, socket 0)
Okt 19 14:44:05 holger kernel: Code: 00 00 66 2e 0f 1f 84 00 00 00 00 00 90 f3 0f 1e fa 89 f8 48 89 fa c5 f9 ef c0 25 ff 0f 00 00 3d e0 0f 00 00 0f 87 33 01 00 00 <c5> fd 74 0f c5 fd d7 c1 85 c0 74 57 f3 0f bc c0 c5 f8 77 c3 66 66

Meanwhile, I believe this is a bug in the Glib library. I'm using the Ubuntu operating system and Glib 2.76.1. Does anyone have experience with this issue?


Solution

  • The values passed to g_log_structured() must all be strings (although the value for the MESSAGE field is handled differently), so you must pass "312" rather than 312 for CODE_LINE.

    g_log_structured() will unconditionally read it as a const char*, which means it’ll dereference the pointer 312 and crash. (This assumes you’re on an architecture where pointers and integers are the same width. If they’re not, it’ll read a different garbage value and crash slightly differently.)