我有一个程序接受两个参数,一个整数和一个字符串。第一个表示要从文件中读取的行数,其名称是第二个 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 行抛出一个段错误。
最佳答案
你遇到了 Stack Overflow!
局部变量放在栈上。您的 C 编译器/链接器似乎分配了一个 8 Mb 的堆栈(假设 long 是 8 个字节)。 1050000 * 8 大于 8 Mb。
当您尝试分配一个不适合的数组时,您会遇到段错误。
尝试在堆上分配数组:
// an array to store the integers from the file
long *dataSet = malloc(dataSize * sizeof(long));
关于C fopen 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34157025/