在是否被调用的函数需要巧舌如簧列表,免费为释放内存 [英] Does the glib list in the called function need to be free for deallocating memory

查看:191
本文介绍了在是否被调用的函数需要巧舌如簧列表,免费为释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用能说会道列表,其中我有它返回的列表中调用函数的函数的简单程序

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

。这里在所调用的函数我已经decleared另一个列表,列表被返回到调用函数。我已经释放名单中的主要功能,但是在进退两难,对于是否被释放的内存性能在被调用的函数需要的清单。

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

}

我是否需要手动自由链表本身从line_parser功能?

Do i need to manually free glist from line_parser function?

推荐答案

像TingPing提到的, strtok_r 不分配任何内存,所以没有你不需要释放。

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

如果您确实需要释放它(例如,如果你是到的strdup strtok_r ),那么你最有可能要使用 g_slist_free_full

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.

这篇关于在是否被调用的函数需要巧舌如簧列表,免费为释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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