【发布时间】: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)操作。