简体   繁体   中英

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM