I'm trying to implement a resizable vector in C without using the realloc and calloc functions. However, when I try to push a lot of values to the back of the array, I get a free(): invalid next size error. How can I remedy this?
I tried freeing the array right before I re-malloc it( the commented out block) but that causes a seg fault rather than the current error.
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;
}
}