【问题标题】:C memory allocation issueC内存分配问题
【发布时间】:2015-05-11 05:38:23
【问题描述】:

我在 c 中有一个算法,其中多次使用 malloc 分配内存。我想编写一个函数,在程序全部完成后释放该内存,但我不确定如何构造它。会不会只是多次调用free()?我对 C 和内存分配相当陌生,因此我们将不胜感激。

程序:

typedef struct State State;
typedef struct Suffix Suffix;

struct State {  /* prefix + suffix list */
    char*   pref[NPREF];    /* prefix words */
    Suffix* suf;            /* list of suffixes */
    State*  next;           /* next in hash table */
};

struct Suffix { /* list of suffixes */
    char *  word;           /* suffix */
    Suffix* next;           /* next in list of suffixes */
};

【问题讨论】:

  • 我建议只包含相关的sn-ps代码
  • 标准警告:请do not castmalloc() 和C 中的家人的返回值。
  • “清除内存”是什么意思?用零代替?什么原因?

标签: c malloc free


【解决方案1】:

每次调用malloc 都应该对应调用free,使用malloc 返回的指针值。

您需要使用某种容器(例如数组、链表)将malloc 返回的值存储在程序中,并在从main 返回之前对这些值调用free。

按照以下方式编写一个函数:

void freeMemory()
{
   int i = 0;
   State* sp = NULL;
   State* tmp = NULL;

   for ( i = 0; i < NHASH; ++i )
   {
      sp = statetab[i];
      while ( sp != NULL )
      {
         tmp = sp->next;
         free(sp);
         sp = tmp;
      }
   }
}

并在return 语句之前从main 调用它。

【讨论】:

  • "对 malloc 的每次调用必须有一个对应的空闲"。我想说每个malloc应该都有一个对应的free。 GTK等库don't always bother with freeing memory
  • @John,您需要遍历列表并在每个指针上调用 free。
猜你喜欢
  • 2021-05-04
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 2016-06-19
  • 2011-01-07
  • 2011-03-18
相关资源
最近更新 更多