Does the glib list in the called function need to be free for deallocating memory

孤人 提交于 2019-12-20 05:54:57

问题


I have a simple program that uses glib list where I have a function which returns the list to the calling function

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

#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?


回答1:


Like TingPing mentioned, strtok_r doesn't allocate any memory, so no you don't need to free it.

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.



来源:https://stackoverflow.com/questions/31792236/does-the-glib-list-in-the-called-function-need-to-be-free-for-deallocating-memor

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