GSList(GLib)出现问题 [英] Problem with GSList (GLib)

查看:84
本文介绍了GSList(GLib)出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI

我正在尝试使用glib.h中的GSList,但是在用char *元素填充列表时遇到了问题.

I'm trying to use GSList from glib.h but I'm having problems when filling the list with char * elements.

这是代码:

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...

我在做什么错了?

谢谢!

推荐答案

该列表将仅保留指针值.如果指针所指向的内存以后被覆盖,则可能会出现问题.

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));

这将存储指向新字符串的指针,这些指针存储在新分配的内存中,每个字符串各不相同.当然,此后您需要通过在每个存储的指针上调用 g_free()来清理此问题,否则程序将泄漏内存:

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);

这将调用标准 g_free() 函数,然后释放列表本身.

This calls the standard g_free() function on each data pointer, before freeing the list itself.

这篇关于GSList(GLib)出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆