Не удается освободить память в C - Динамическая структура и массив - PullRequest
0 голосов
/ 08 марта 2019

Я пытался освободить память моей программы в течение последних 2 дней. По какой-то причине я никогда не смогу полностью освободиться. У меня есть цикл, и он дважды внутри него:

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 голосов
/ 08 марта 2019

первый случай, они освобождаются в цикле:

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 ?
}
0 голосов
/ 08 марта 2019

В коде после этого фрагмента у вас, вероятно, есть:

ent->utf8text = carr;

Вы бы освободили каждого struct entry в 2 этапа:

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

Обратите внимание, что этот код немного противоречив: malloc(sizeof(char) * sizeOfUtf + 1);. Размер правильный, потому что sizeof(char) равен 1, но для согласованности следует либо читать:

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

Или

malloc(sizeOfUtf + 1);
...