Search code examples
cstringrefcountingref-struct

What is GRefString implementation in GLib?


I wonder where is the reference count stored? As the type is defined as:

typedef char GRefString;

And all the g_ref_string*…() functions are returning simply gchar * instead of a structure, which could hold the reference count. Is it the trick of sds library, to hold a metadata header structure right before the char * pointed memory? I'm afraid that such implementation can backfire at some point, am I right? I.e.: what problems can arise when using such pre-header equipped strings?


Solution

  • The reference counting data is stored before the string.

    Following the source code, you'll end up in g_rc_box_alloc_full() that has the following relevant line:

    real_size = private_size + block_size;
    

    block_size is what you want to allocate in the heap (in the GRefString case, the length of the string plus 1) and private_size is sizeof(GArcBox), i.e. the struct containing the refcounting data.