c - 来自 C 中输入文件的 fgets 的段错误

标签 c segmentation-fault

此函数使用fgets 从文件输入数据并将其存储在结构中。我遇到了段错误,我不知道为什么。该程序不会运行,所以我无法调试。这是函数的代码:

void getInventory(NodeT **ppRoot, char *pszInventoryFileName)
{
    char szInputBuffer[100];       // input buffer for reading data
    int iScanfCnt;                 // returned by sscanf
    FILE *pfileInventory;          // Stream Input for Inventory data.
    Stock *pNew = NULL;

    /* open the Inventory stream data file */
    if (pszInventoryFileName == NULL)
            exitError(ERR_MISSING_SWITCH, "-i");

    pfileInventory = fopen(pszInventoryFileName, "r");
    if (pfileInventory == NULL)
            exitError(ERR_INVENTORY_FILENAME, pszInventoryFileName);

    /* get inventory data until EOF
    ** fgets returns null when EOF is reached.
    */
    while (fgets(szInputBuffer, 100, pfileInventory) != NULL)
    {
            iScanfCnt = sscanf(szInputBuffer, "%6s %ld %lf %30[^\n]\n"
                    , pNew->szStockNumber
                    , &pNew->lStockQty
                    , &pNew->dUnitPrice
                    , pNew->szStockName);

            if (iScanfCnt < 4)
                    exitError(ERR_INVALID_INVENTORY_DATA, "\n");

            if (pNew == NULL)
                    exitError("Memory allocation error", "");

            printT(insertT(*ppRoot, *pNew));
    }
}

printTinsertT 函数是递归的,但程序在执行到那一步之前就失败了。这是来自输入文件的数据:

PPF001 100 9.95 Popeil Pocket Fisherman
SBB001 300 14.95 Snuggie Brown
SBG002 400 14.95 Snuggie Green
BOM001 20 29.95 Bass-O-Matic
MCW001 70 12.45 Miracle Car Wax
TTP001 75 9.95 Topsy Turvy Planter
NHC001 300 9.95 Electric Nose Hair Clipper
SSX001 150 29.95 Secret Seal

为什么这段代码给我一个段错误?

最佳答案

问题是,虽然您正在检查 pNew 分配给 NULL,但实际上您从未向它分配内存。

添加对 malloc 的调用,分配给 pNew 并在 sscanf 调用之前进行内存检查以修复此问题:

while (fgets(szInputBuffer, 100, pfileInventory) != NULL)
{
        pNew = malloc(sizeof(Stock));
        if (pNew == NULL)
                exitError("Memory allocation error", "");

        iScanfCnt = sscanf(szInputBuffer, "%6s %ld %lf %30[^\n]\n"
                , pNew->szStockNumber
                , &pNew->lStockQty
                , &pNew->dUnitPrice
                , pNew->szStockName);

        if (iScanfCnt < 4)
                exitError(ERR_INVALID_INVENTORY_DATA, "\n");

        printT(insertT(*ppRoot, *pNew));
}

关于c - 来自 C 中输入文件的 fgets 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29661037/

相关文章:

c - 指向字符串数组的指针数组

将 int 转换为字符串并连接结果

无法解决 SDL 中的段错误(核心转储)

c - C中的指针 - 构造矩阵时为 "Segmentation Fault"

c - 定义可以访问位、半字节、字节的 union

c - 使用套接字程序接受顺序用户输入

c - C 中的多个函数和指针

mongodb - 从 channel 读取 SIGSEGV : segmentation violation

python - 在 .so 文件中使用 C 模块时出现段错误

c - 反转 24 位颜色