【问题标题】:C fopen seg faultC fopen 段错误
【发布时间】:2015-12-08 13:22:21
【问题描述】:

我有一个程序,它接受两个参数,一个整数和一个字符串。第一个表示要从文件中读取的行数,其名称是第二个参数。文件每行有一个整数值。

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 行引发分段错误。

【问题讨论】:

  • 在 Windows 上默认进程堆栈大小为 1MB,在 Linux 上为 8MB。大多数编译器将变量(包括数组)放在堆栈上。在 64 位系统上,单个 long 可以是 64 位(8 字节)。你做数学。 :)
  • long dataSet[dataSize]; 更改为static 或使用malloc 因为大以确保堆栈

标签: c segmentation-fault


【解决方案1】:

你得到一个堆栈溢出!

局部变量被放置在堆栈上。您的 C 编译器/链接器似乎分配了一个 8 Mb 堆栈(假设 long 是 8 个字节)。 1050000 * 8 大于 8 Mb。

当您尝试分配一个不适合的数组时,您会遇到 seg 错误。

尝试在堆上分配数组:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多