简体   繁体   English

使用动态数组的空指针错误重新分配

[英]Error realloc with Dynamic Array of Void Pointers

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: 但是,当一个数组已满并且我调用realloc时,我得到一个编译器错误,它是:realloc():下一个大小无效我的代码如下:

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);
    }

}

It is not clear if you need void** or void* . 目前尚不清楚您是否需要void**void*

This line is problematic: stack->array= malloc(stack->capacity*size_data_type); 这一行有问题: stack->array= malloc(stack->capacity*size_data_type);

You never initialize this memory area correctly. 您永远不会正确初始化此内存区域。 It should allocate room for as many void* as you have objects. 它应该为你拥有的对象分配空间void* This has nothing to do with the data size of the pointed-at items. 这与指向项的数据大小无关。 Each such pointer needs to be initialized. 每个这样的指针都需要初始化。 You need to keep track of the total number of pointers as well as the size of each pointed-at item. 您需要跟踪指针的总数以及每个指向项的大小。

Alternatively you should drop void** in favour of void* , if this is meant to point at a one-dimensional array or single object. 或者,如果要指向一维数组或单个对象,则应删除void**以支持void*

stack->array[++stack->top]=data; looks fishy, this leaves index 0 uninitialized. 看起来很腥,这使得索引0未初始化。

Make sure to include stdlib.h or you will get severe bugs on stone age C90 compilers, bugs that your casts hide. 确保包含stdlib.h否则你会在石器时代的C90编译器上遇到严重的错误,你的演员隐藏的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM