c - Realloc 使我的程序在读取二进制文件功能时崩溃

标签 c realloc

<分区>

所以我在 C 中有这个功能,可以将数据从二进制文件读取到动态数组。当我运行它时它崩溃了,我试图放置一些 printf 以了解它被卡住的位置,看起来就像是在我尝试重新分配时。 我只是找不到任何错误。希望有人能帮助我。

tipoEmprestimo *lerFichBin_Emprestimos(tipoEmprestimo *vetorEmprestimos,int *quantEmprestimos)
{
    int quantlidos;
    FILE *ficheiro;


    ficheiro=fopen("emprestimos.dat","rb");

    if (ficheiro == NULL)
    {
        printf("\nNao foi possivel ler o ficheiro!");
        free(vetorEmprestimos);
        vetorEmprestimos=NULL;
        *quantEmprestimos=0;
    }
    else
    {

        quantlidos=fread(&quantEmprestimos,sizeof(int),1,ficheiro);
        if (quantlidos != 1)
        {
            printf("\nErro ao ler ficheiro!");
        }
        vetorEmprestimos=realloc(vetorEmprestimos,(*quantEmprestimos)*sizeof(tipoEmprestimo));


        if (vetorEmprestimos == NULL)
        {
            printf("\nErro ao reservar memoria!");

        }
        else
        {

            quantlidos=fread(vetorEmprestimos,sizeof(tipoEmprestimo),*quantEmprestimos,ficheiro);
            if(quantlidos != *quantEmprestimos)
            {
                printf("\nErro ao ler ficheiro!");
            }
        }

    }
    fclose(ficheiro);
return vetorEmprestimos;
}

最佳答案

可能的原因

  • vetorEmprestimos 在调用 realloc 时未初始化
  • vetorEmprestimos 调用 realloc 时指向堆栈
  • vetorEmprestimos 调用realloc时指向常量内存区域

关于c - Realloc 使我的程序在读取二进制文件功能时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53995550/

相关文章:

c - 在此代码片段中,realloc 做了什么?

c++ - C++ 17 POSIX信号量或condition_variable?

c - 为什么结构体的内存副本没有按预期将字节复制到字节流?

c - strncmp() 表达式中的 strlen() 是否会破坏在 strcmp() 上使用 strncmp() 的目的?

c - 来自终端的 SIGHUP

c - C 中带有函数的 realloc 结构

c - 动态数组添加元素后打印乱码

c - 二进制补码形式的 64 位负整数

无法打印出动态分配数组中的元素

c - C 中增长内存中的多维数组