簡體   English   中英

C fopen段故障

[英]C fopen seg fault

我有一個程序需要兩個參數,一個整數和一個字符串。 第一個表示要從文件讀取的行數,其名稱為第二個arg。 文件每行具有一個整數值。

int main(int argc, char* argv[])
{

// the size of the data set 
long dataSize = atol(argv[1]);

// an array to store the integers from the file

long dataSet[dataSize];
// open the file
fp = fopen(argv[2], "r");
// exit the program if unable to open file
if(fp == NULL)
{
printf("Couldn't open file, program will now exit.\n");
exit(0);
} // if

我有一個名為data10M的文件,具有1000萬個整數。 在我將第一個參數更改為大於1050000之前,它一直運行良好,此時程序在fopen行上引發了分段錯誤。

您正在獲得堆棧溢出!

局部變量放在堆棧上。 您的C編譯器/鏈接器似乎分配了8 Mb的堆棧(假設long為8個字節)。 1050000 * 8大於​​8 Mb。

當您嘗試分配不合適的數組時,您會遇到段錯誤。

嘗試在堆上分配g數組:

// an array to store the integers from the file
long *dataSet = malloc(dataSize * sizeof(long));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM