c - 第二次运行后带有 realloc 的函数使程序崩溃

标签 c pointers malloc realloc

似乎在realocVet函数第二次运行后,出现错误信息“malloc: *** error for object 0x7f8bfac039b0: pointer being realloc'd was not allocated”。

void realocVet (float *precoList, char *nomeList, short int *quantidadeList)
{
    static short int p=2,n=100,q=2;
    p=4*p;
    n=4*n;
    q=4*q;
    precoList =realloc(precoList,p * sizeof(float));
    nomeList =realloc(nomeList,n * sizeof(char));
    quantidadeList =realloc(quantidadeList,q * sizeof(short int ));
}

void insertData (float *precoList, char *nomeList, short int *quantidadeList, struct newCard myCard)
{
    static short int slotsAvailable = 2, aux=2,currentCard=0,nnchar=0;
    short int nchar;
    precoList[currentCard] = myCard.preco;
    quantidadeList[currentCard] = myCard.quantidade;
    for (nchar=0;nchar<50;nchar++)
    {
        nomeList[nnchar] = myCard.nome[nchar];
        nnchar++;
    }
    currentCard++;
    slotsAvailable--;

    if (slotsAvailable==0)
    {
        realocVet(precoList, nomeList, quantidadeList);
        slotsAvailable = aux;
        aux = 2*aux;
    }
}

最佳答案

您传入一个指针 float *precoList,然后重新分配(可能会更改)。问题是当你返回时,调用者仍然拥有指针的旧值。

当您再次调用该函数时,它将使用指向已释放内存的旧值进行调用。

void realocVet (float **precoList, char **nomeList, short int **quantidadeList)
{
    static short int p=2,n=100,q=2;
    p=4*p;
    n=4*n;
    q=4*q;
    *precoList =realloc(*precoList,p * sizeof(float));
    *nomeList =realloc(*nomeList,n * sizeof(char));
    *quantidadeList =realloc(*quantidadeList,q * sizeof(short int ));
}

关于c - 第二次运行后带有 realloc 的函数使程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16345147/

相关文章:

c - CryoPID 如何创建 ELF header ,或者是否有一种简单的方法来生成 ELF?

c - 如何将函数和变量参数列表传递给 C 中的另一个函数?

c++ - 使用指针打印链表中的节点

c - 这段代码不会造成内存泄漏吗?

c - 动态二维字符数组分配无法正常工作

c - 在没有循环的情况下生成范围外的随机数

c - GtkLabel 不显示文件中的换行符

c++ - 指针问题.. ( C++ )

c - 无法在函数内分配内存并在 C 中返回它

c - 将每行末尾的元素追加到文件中