【问题标题】:Function with realloc crashes program after second run具有 realloc 的函数在第二次运行后崩溃程序
【发布时间】:2013-05-02 18:25:26
【问题描述】:

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

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

【问题讨论】:

  • 你怎么称呼insertData?
  • void realocVet (float *precoList,...

标签: c pointers malloc realloc


【解决方案1】:

你传入一个指针,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 ));
}

【讨论】:

  • 哦,我明白了……这很有意义。那么函数realocVet的调用呢?我应该做一些改变吗? ps:仍然无法正常工作,但我希望它会:p
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多