Clarifying how g_strfreev() frees each element of the passed vector
I want to write a function similar to g_strsplit
but returning a GPtrArray
instead of a NULL-terminated array of strings. My approach is to reuse g_strsplit
and steal the tokens returned by it. However, I need to tweak the array of tokens to trick g_strfreev()
to prevent it from freeing them:
GPtrArray *mysplit(const gchar *str, const gchar *delimiter, gint max_tokens) {
GPtrArray *arr = g_ptr_array_new_with_free_func(g_free);
//Split the string and add the tokens to the resulting array
gchar **tokens = g_strsplit(str, delimiter, max_tokens);
for (**token = tokens; *token != NULL; token++) {
g_ptr_array_add(arr, *token);
}
//Tweak the tokens array and free the vector
tokens[0] = NULL;
g_strfreev(tokens);
return arr;
}
The problem with my code is that it assumes that g_strsplit()
uses an allocator compatible with g_free
. I have checked the source code of g_strfreev()
and it indeed frees each token using g_free()
, but my fear is that future implementations of functions returning NULL-terminated array of strings may break my code.
Therefore I think it would be useful to clarify how g_strfreev()
frees each element of the passed vector in the docs.