问题
HI,
I'm trying to use GSList from glib.h but I'm having problems when filling the list with char * elements.
Here's the code:
GSList * res = NULL;
char * nombre;
while (...) {
nombre = sqlite3_column_text(resultado, 1);
res = g_slist_append (res, nombre);
}
printf("number of elements: %i\n", g_slist_length(res));
printf("last element: %s\n", g_slist_last(res)->data);
When I print the number of elemnts, I see the list is not empty. But when I print the last element, It doesn't show anything...
What Am I doing wrong?
Thanks!
回答1:
The list will only retain the pointer value. If the memory the pointer is pointing at is later overwritten, you will have problems.
The solution could be to duplicate the string before storing it:
res = g_list_append(res, g_strdup(nombre));
This will store pointers to new strings, stored in freshly-allocated memory, different for each string. Of course, you need to clean this up afterwards by calling g_free()
on each of the stored pointers, or your program will leak memory:
g_list_free_full(res, g_free);
This calls the standard g_free()
function on each data pointer, before freeing the list itself.
来源:https://stackoverflow.com/questions/5948547/problem-with-gslist-glib