简体   繁体   English

C内存分配问题

[英]C memory allocation issue

I have an algorithm in c in which memory is allocated using malloc many times. 我在c中有一种算法,其中多次使用malloc分配内存。 I wanted to write a function that would free that memory when the program is all finished but I am unsure how to structure it. 我想编写一个函数,在程序全部完成后释放该内存,但是我不确定如何构造它。 Would it just be multiple calls to free() ? 只是多次调用free()吗? I am rather new to C and memory allocation so any help would be greatly appreciated. 我对C和内存分配比较陌生,因此将不胜感激。

Program: 程序:

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

Every call to malloc should have a corresponding call to free , using the value of the pointer that was returned by malloc . 每次对malloc调用都应使用malloc返回的指针的值对free进行相应的调用。

You'll need to store the values returned by malloc in your program using some sort of container, such as an array, a linked list, and call free on those values before returning from main . 您需要使用某种容器(例如数组,链表)将malloc返回的值存储在程序中,并在从main返回之前free调用这些值。

Write a function along the lines of: 按照以下方式编写函数:

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

and call it from main before the return statement. 并在return语句之前从main调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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