GSList (GLib) 问题
您好,
我正在尝试使用 glib.h 中的 GSList,但在使用 char * 元素填充列表时遇到问题。
这是代码:
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);
当我打印元素数量时,我看到列表不为空。但是当我打印最后一个元素时,它没有显示任何内容......
我做错了什么?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该列表将仅保留指针值。如果指针指向的内存后来被覆盖,就会遇到问题。
解决方案可能是复制存储之前的字符串:
这将存储指向新字符串的指针,这些新字符串存储在新分配的内存中,每个字符串都不同。当然,之后您需要通过在每个存储的指针上调用
g_free()
来清理它,否则您的程序将泄漏内存:这会调用标准的
g_free()
函数在每个数据指针上,然后释放列出自己。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:
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:This calls the standard
g_free()
function on each data pointer, before freeing the list itself.