来自 C 输入文件的 fget 的分段错误



此函数使用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

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

问题是,尽管您正在检查NULL pNew分配,但您从未实际为其分配内存。

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

相关内容

  • 没有找到相关文章

最新更新