无法释放C语言中的内存-动态结构和数组

时间:2019-03-08 06:11:59

标签: c arrays memory malloc free

过去2天,我一直在尝试释放程序的内存。由于某些原因,我永远无法完全自由。我有一个循环,它在其中两次malloc:

struct entry
{
  int utf8length;
  char * utf8text;

};

for( int i = 0; i < constant_pool_count; i++ )
{
      ent = malloc(sizeof(struct entry));
      if(ent==NULL)
      {
        fprintf(stderr, "Failed malloc, Exiting the program \n");
        exit(-1);
       }
      ent->utf8length = sizeOfUtf;
      carr = malloc(sizeof(char) * sizeOfUtf + 1);
      if(carr==NULL)
      {
        fprintf(stderr, "Failed malloc, Exiting the program \n");
        exit(-1);
      }
       //More code

}

我应该如何释放它们?

2 个答案:

答案 0 :(得分:0)

在此片段之后的代码中,您可能具有:

ent->utf8text = carr;

您可以分两步释放每个struct entry

free(ent->utf8text);
free(ent);

请注意,此代码略有不一致:malloc(sizeof(char) * sizeOfUtf + 1);。大小是正确的,因为sizeof(char)1,但是为了保持一致,它应该显示为:

malloc(sizeof(char) * (sizeOfUtf + 1));

malloc(sizeOfUtf + 1);

答案 1 :(得分:0)

第一种情况,它们在循环中被释放:

struct entry
{
  int utf8length;
  char * utf8text;

};

...

for( int i = 0; i < constant_pool_count; i++ )
{
      struct entry * ent;
      char * carr;

      ent = malloc(sizeof(struct entry));
      if(ent==NULL)
      {
        fprintf(stderr, "Failed malloc, Exiting the program \n");
        exit(-1);
       }
      ent->utf8length = sizeOfUtf;
      carr = malloc(sizeof(char) * sizeOfUtf + 1);
      if(carr==NULL)
      {
        fprintf(stderr, "Failed malloc, Exiting the program \n");
        exit(-1);
      }

      ent->utf8text = carr; // I suppose

      //More code

      free(ent->utf8text);
      free(ent);
}

第二种情况,您需要使它们脱离循环然后释放它们

struct entry
{
  int utf8length;
  char * utf8text;

};

...

struct entry * all[constant_pool_count];

for( int i = 0; i < constant_pool_count; i++ )
{
      struct entry * ent;
      char * carr;

      ent = malloc(sizeof(struct entry));
      if(ent==NULL)
      {
        fprintf(stderr, "Failed malloc, Exiting the program \n");
        exit(-1);
       }
      ent->utf8length = sizeOfUtf;
      carr = malloc(sizeof(char) * sizeOfUtf + 1);
      if(carr==NULL)
      {
        fprintf(stderr, "Failed malloc, Exiting the program \n");
        exit(-1);
      }

      ent->utf8text = carr; // I suppose
      all[i] = ent;

      //More code
}

... some code

// free them

for( int i = 0; i < constant_pool_count; i++ )
{
   free (all[i]->utf8text);
   free (all[i]);
   // may be "all[i] = NULL;" if useful ?
}