【问题标题】:free(): invalid next size (fast) for resizable vectorfree():可调整大小向量的下一个大小(快速)无效
【发布时间】:2019-10-10 16:23:56
【问题描述】:

我正在尝试在不使用 realloc 和 calloc 函数的情况下在 C 中实现可调整大小的向量。但是,当我尝试将大量值推送到数组的后面时,我得到一个 free(): invalid next size 错误。我该如何解决这个问题?

我尝试在重新分配数组之前释放数组(注释掉的块),但这会导致段错误而不是当前错误。

typedef struct {
size_t size;
size_t maxsize;
  int* array;
}
vector_int_t;

// Push a new value into the vector_int_t, allocate just enough memory if
// the internal array is full.
void vector_int_push_back_v1( vector_int_t* this, int value )
{ 
  if( this->size == this->maxsize ) {
    int* temp = malloc(  4 * (sizeof( this->maxsize)+1)  );
    size_t j = 0;
    for( size_t i = 0; i < this->maxsize; i++ ) {
      temp[j] = this->array[i];
      j++;
    }    
    temp[this->size] = value;
    /*if( this->size == 0 ) {
      this->array = malloc( 4 * (sizeof(this->maxsize)+2));
      this->size++;
      this->maxsize++;
      size_t z = 0;
      for( size_t y = 0; y < this->maxsize; y++ ) {
        this->array[z] = temp[y];
        z++;
      }
    }
    else {
      free( this->array );*/
      this->array = malloc( 4 * (sizeof(this->maxsize)+2)  );
      this->size++;
      this->maxsize++;
      size_t h = 0;
      for( size_t k = 0; k < this->maxsize; k++ ) {
        this->array[h] = temp[k];
        h++;
      }
    free( temp );
  }
  else {
    this->size++;
    this->maxsize++;
    this->array[this->size - 1] = value;
  }

}

【问题讨论】:

  • 您好,欢迎来到 Stack Overflow!提问时,请确保您的代码可以编译。清理代码并只留下重现问题的必要部分并没有什么坏处。你可以在这里阅读更多内容:如何制作minimal reproducible example
  • 旁注:只要达到容量,将向量仅扩展一两个元素会产生极差的性能,特别是因为您没有使用realloc(因此从不 i> 重用/调整内存分配的大小,而不是 总是 复制到新内存);追加成为O(n) 操作。通常,您希望使用当前容量的一些倍数;最简单的方法是每次将容量加倍,尽管当最终大小仅略超过 2 的幂时,这可能会导致过多的未使用内存。任何合理的倍数都会附加一个摊销的O(1) 操作。

标签: c vector push-back


【解决方案1】:

当您写入超出分配的内存范围时,通常会发生此错误。

一个很可能的罪魁祸首是在例如使用sizeofmalloc( 4 * (sizeof( this-&gt;maxsize)+1) ).

如果你想分配this-&gt;maxsize + 1 元素,你应该只使用那个而不是sizeof

但您应该使用sizeof 来获取每个元素的大小(例如sizeof *temp)。

所以声明

int* temp = malloc(  4 * (sizeof( this->maxsize)+1)  );

应该真的像

int* temp = malloc(  sizeof *temp * (this->maxsize+1)  );

【讨论】:

    猜你喜欢
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 2017-03-12
    • 2012-02-22
    • 2012-10-25
    • 2012-05-22
    相关资源
    最近更新 更多