理解使用 malloc 重新分配的困难

Difficulties with understanding reallocating using malloc

我正在尝试使用 malloc 而不是 realloc 来增加我的 collection 结构的大小。恐怕我在分配变量时犯了错误,因为我得到:

malloc: *** error for object 0x7fd46b404ac8: pointer being freed was not allocated

如果你能给我一个有用的提示,我将不胜感激。

void increaseCollectionSize(){
  collection.size = (collection.size + 1) * REALLOCATE_MODIFIER;
  char **increasedCollection = malloc(sizeof(char *) * collection.size);
  char **increasedHead = increasedCollection;
  for(int i = 0; i < collection.numberOfWords; i++){
    *increasedCollection = *collection.words;
    increasedCollection++;
    collection.words++;
  }
  free(collection.words); // I'm getting error here.
  collection.words = increasedHead;
}

typedef struct Collection{
  char **words;
  size_t numberOfWords;
  size_t size;
} Collection;

您释放了 collection.words 的最终值,它是指向原始内存块末尾的指针(由于循环中的 ++)。

void increaseCollectionSize(){
    collection.size = (collection.size + 1) * REALLOCATE_MODIFIER;
    char **increasedCollection = malloc(sizeof(char *) * collection.size);
    char **increasedHead = increasedCollection;
    char **originalWords = collection.words; // save a pointer
    for(int i = 0; i < collection.numberOfWords; i++){
        *increasedCollection = *collection.words;
        increasedCollection++;
        collection.words++;
    }
    free(originalWords); // now ok
    collection.words = increasedHead;
}

或者,降低复杂性:

void increaseCollectionSize() {
    collection.size = (collection.size + 1) * REALLOCATE_MODIFIER;
    char **increasedCollection = malloc(sizeof(char *) * collection.size);
    assert(increasedCollection != NULL); // explicitly abort() on malloc() error

    for (size_t i = 0; i < collection.numberOfWords; i++)
        increasedCollection[i] = collection.words[i];

    free(collection.words);
    collection.words = increasedCollection;
}