I'm trying to create a dynamic set abstract data type, based on a dynamic array. However, I get a compiler an error when an array is full and I invoke the realloc, which are: realloc(): invalid next size My code is as follows:
struct arraystack{
int top;
int capacity;
void **array;
size_t data_size; //size of my data type
};
struct arraystack * createStack(int capacity,size_t size_data_type){
struct arraystack *stack= (struct arraystack*) malloc(sizeof(struct arraystack));
stack->capacity=capacity;
stack->top=-1;
stack->data_size=size_data_type;
stack->array= malloc(stack->capacity*size_data_type);
return stack;
}
void push(struct arraystack *stack, void* data){
if(isFull(stack)){
printf("Invoco realloc\n");
stack->capacity=(stack->capacity*2)+1;
void **tmp=realloc(stack->array,(stack->capacity*stack->data_size)); //this line gives me an error
if(!tmp){
printf("Attenzione memoria insufficente!\n");
exit(1);
}
stack->array=tmp;
}
stack->array[++stack->top]=data;
printf("%d pushed to stack\n", data);
}
int isFull(struct arraystack *stack){
return stack->top == stack->capacity - 1;
}
int main(){
struct arraystack *tmp=createStack(5,sizeof(int));
int i;
for(i=0;i<=20;i++){
push(tmp,i);
printf("top-> %d memoria allocata->%d\n",tmp->top,tmp->capacity);
}
}
答案 0 :(得分:0)
不清楚您是否需要Arc
或void**
。
此行有问题:void*
您永远不会正确初始化此存储区。它应该为您拥有对象的stack->array= malloc(stack->capacity*size_data_type);
分配空间。这与所指向项目的数据大小无关。每个此类指针都需要初始化。您需要跟踪指针的总数以及每个指向项目的大小。
或者,如果要指向一维数组或单个对象,则应该将void*
改为void**
。
void*
看起来很腥,这使索引0未被初始化。
确保包括stack->array[++stack->top]=data;
,否则您会遇到石器时代C90编译器的严重错误,这些错误会隐藏在演员表中。