第二次运行后realloc崩溃程序的功能

时间:2013-05-02 18:25:26

标签: c pointers malloc realloc

似乎在函数realocVet运行的第二次之后,出现错误消息“malloc:***错误,对象为0x7f8bfac039b0:指针被重新分配”。

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

1 个答案:

答案 0 :(得分:4)

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

再次调用该函数时,将使用指向freed memory的旧值调用它。

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