C fopen 段错误

标签 c segmentation-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 行抛出一个段错误。

最佳答案

你遇到了 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/

相关文章:

arrays - 数组中元素出现的频率

C++ map.erase() 导致不必要的平衡

android - 为什么在 Android 设备上执行 "pm"时会出现段错误?

c - 数组困难 - 仅 2 次赋值后出现段错误

c++ - 我如何使用 GCC 选项 -iprefix 和 -iwithprefix?

c - #Pragma pack 编译时发出警告

c - 从二进制文件中读取动态大小的字符串

c - strcat 时的未定义行为

c++ - 主导出后出现段错误

c - 为什么在尝试将数组从标准输入复制到二维数组时出现段错误?