[英]Does the glib list in the called function need to be free for deallocating memory
I have a simple program that uses glib list where I have a function which returns the list to the calling function 我有一个使用glib list的简单程序,其中有一个将列表返回给调用函数的函数
.here in the called function i have decleared another list and the list is returned to the calling function. 。在被调用函数中,我已经清除了另一个列表,该列表返回给调用函数。 I have freed the list in the main function but is in delimma that whether the list in the called function need to be freed for memory performance.
我已经释放了main函数中的列表,但是很不高兴是否需要释放调用函数中的列表以提高内存性能。
#include <stdio.h>
#include <string.h>
#include <glib.h>
char *col_trim_whitespace(char *str)
{
char *end;
// Trim leading space
while(isspace(*str)) str++;
if(*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace(*end)) end--;
// Write new null terminator
*(end+1) = 0;
return str;
}
GSList* line_parser(char *str)
{
GSList* list = NULL;
char *token, *remstr=NULL ;
//use glist for glib
token = strtok_r(str,"\n",&remstr);
while(token != NULL)
{
if(token[0] == ' ')
{
token = col_trim_whitespace(token);
if(strcmp(token,"")==0)
{
token = strtok_r(NULL, "\n", &remstr);
continue;
}
}
list = g_slist_append(list, token);
token = strtok_r(NULL,"\n",&remstr);
}
return list;
}
int main()
{
int *av,i,j,length;
i=0;
char str[] = " this name of \n the pet is the ffffffffffffffffffffffffffffff\n is \n the \n test\n program";
GSList *list1 = line_parser(str);
// printf("The list is now %d items long\n", g_slist_length(list));
length = g_slist_length(list1);
// printf("length=%d", length);
for(j=0;j<length;j++)
{
printf("string = %s\n",(char *)g_slist_nth(list1,j)->data);
}
g_slist_free(list1);
return 0;
}
Do i need to manually free glist from line_parser function? 我是否需要从line_parser函数手动释放glist?
Like TingPing mentioned, strtok_r
doesn't allocate any memory, so no you don't need to free it. 就像提到的
strtok_r
一样, strtok_r
不会分配任何内存,因此,您不需要释放它。
If you did need to free it (for example if you were to strdup
the value from strtok_r
) then you would most likely want to use g_slist_free_full . 如果确实需要释放它(例如,如果要从
strtok_r
strdup
值),则很可能要使用g_slist_free_full 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.