[英]segmentation fault with fgets from input file in C
此函數使用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));
}
}
printT
和insertT
函數是遞歸的,但是程序在到達該距離之前就失敗了。 這是來自輸入文件的數據:
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
,但從未實際為其分配內存。
向分配給pNew
malloc
添加一個調用,並在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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.