簡體   English   中英

C內存分配問題

[英]C memory allocation issue

我在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 */
};

每次對malloc調用都應使用malloc返回的指針的值對free進行相應的調用。

您需要使用某種容器(例如數組,鏈表)將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調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM