【问题标题】:How to properly use free for specific struct type in C如何在 C 中为特定结构类型正确使用 free
【发布时间】:2013-05-02 06:04:59
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c malloc free dynamic-data realloc


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      例如,你在这里:

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

      要释放它,你可以反过来:

      1. 每个单独字符串的可用空间
      2. 阵列的可用空间

      【讨论】:

        【解决方案3】:

        代码是

        for (int counter = 0; counter {
        免费 (arrayOfWords[counter].words);
        }

        免费 (arrayOfWords);

        【讨论】:

          猜你喜欢
          • 2022-11-25
          • 1970-01-01
          • 1970-01-01
          • 2014-01-22
          • 1970-01-01
          • 2022-06-23
          • 2017-06-23
          • 2015-06-09
          • 1970-01-01
          相关资源
          最近更新 更多