Problem with GSList (GLib)

冷暖自知 提交于 2021-02-11 13:28:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!