简体   繁体   English

C fopen段故障

[英]C fopen seg fault

I have a program that takes two parameters, an integer and a string. 我有一个程序需要两个参数,一个整数和一个字符串。 The first represents the number of lines to be read from the file, whose name is the second arg. 第一个表示要从文件读取的行数,其名称为第二个arg。 Files have an integer value per line. 文件每行具有一个整数值。

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

I have a file called data10M with 10 million integers. 我有一个名为data10M的文件,具有1000万个整数。 It works fine until I change the first argument to something more than about 1050000, at which point the program throws a segmentation fault at the fopen line. 在我将第一个参数更改为大于1050000之前,它一直运行良好,此时程序在fopen行上引发了分段错误。

You are getting a Stack Overflow! 您正在获得堆栈溢出!

Local variables are placed on the stack. 局部变量放在堆栈上。 Your C compiler/linker seems to allocate an 8 Mb stack (assuming long is 8 bytes). 您的C编译器/链接器似乎分配了8 Mb的堆栈(假设long为8个字节)。 1050000 * 8 is more than 8 Mb. 1050000 * 8大于​​8 Mb。

You get the seg fault when you try to allocate an array that doesn't fit. 当您尝试分配不合适的数组时,您会遇到段错误。

Try allocationg the array on the heap instead: 尝试在堆上分配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