0

我查看了其他讨论,但仍然无法弄清楚。我有一个结构,

typedef struct { char * word; int count; } wordType;

在我的代码中,我 malloc 每个 array[index].word 并重新分配结构数组。我该如何正确释放它们?为了清楚起见,我从我的代码中包含了一些片段。

            wordType *arrayOfWords = NULL;
            char temp[50];

            arrayOfWords = realloc(arrayOfWords, (unique_words+1)*sizeof(wordType));
            arrayOfWords[unique_words].count = 1;
            arrayOfWords[unique_words].word = malloc(sizeof(char)*(strlen(temp)+1));
            strcpy(arrayOfWords[unique_words].word, temp);
4

3 回答 3

2

你会做同样的事情,但反过来。

例如,在这里你:

  1. 为数组分配空间
  2. 为每个单独的字符串分配空间

要释放它,请反向执行:

  1. 每个单独字符串的可用空间
  2. 阵列的可用空间
于 2013-05-02T06:08:05.403 回答
2

您必须释放每块分配的内存:即word所有结构中的字段,然后是arrayOfWords数组本身:

for (int i = 0; i < NUM_WORDS; /* whatever it is */ i++) {
    free(arrayOfWords[i].word);
}

free(arrayOfWords);

一些好的建议:不要realloc()在每一步 - 这很乏味。使用呈指数增长的存储空间(超过时空间翻倍)。

于 2013-05-02T06:09:29.797 回答
0

代码是

for (int counter = 0; counter < count; counter++)
{
free (arrayOfWords[counter].words);
}

免费(arrayOfWords);

于 2013-05-02T06:11:54.597 回答