C fopen seg fault

不问归期 提交于 2019-12-12 04:18:19

问题


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. 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. 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.


回答1:


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). 1050000 * 8 is more than 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:

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


来源:https://stackoverflow.com/questions/34157025/c-fopen-seg-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!