C语言 难以理解使用 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;
}

相关内容

  • 没有找到相关文章

最新更新