When to call g_error_free?

It’s not entirely clear from the (otherwise beautiful) API documentation when/if the caller should call g_error_free() for a given GError pointer received from eg:

  • json_parser_load_from_data() 4th argument
  • return from json_reader_get_error()

Can you give guidance?

json_reader_get_error() returns a const GError* that is owned by the Reader instance, and thus should not be freed by the caller. See the documentation that states “The data is owned by the instance”.

json_parser_load_from_data() on the other hand uses GLib’s standard error reporting, which means that the error must be freed by the caller that provided the pointer.

For example:

GError *error = NULL;

if (!json_parser_load_from_data(parser, data, -1, &error))
  {
    g_warning ("Parsing failed: %s", error->message);
    g_error_free (error);
    return;
  }

If on the other hand you pass on an error parameter, it’s up to the respective caller to free it:

gboolean
my_parser_parse (MyParser  *parser,
                 GError   **error)
{
  if (!json_parser_load_from_data (parser->parser, parser->data, -1, error))
    return FALSE;

  g_debug ("Data was parsed successfully");
  return TRUE;
}

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.