【问题标题】:Segmentation fault on function call with two dimensional array使用二维数组调用函数时出现分段错误
【发布时间】:2013-03-14 19:37:11
【问题描述】:

我有以下代码:

#define MAXSAMPLES 1024
typedef  int sample_t;
typedef sample_t sub_band_t[MAXSAMPLES][MAXSAMPLES];

void blah(sample_t a[][MAXSAMPLES], int u0, int v0, int u1, int v1) {
. . . . 
} 


int main(int argc, char *argv[]) {
    sub_band_t in_data;
    int k =0;

    if (argc < 2) {
        printf("\nInput filename required\n");
        return 0;
    }

    FILE *input_file = fopen(argv[1], "r");
    char del = '\0';

    int i = 0, j = 0;
    int cols = 0;
    sample_t x;
    while (! feof(input_file)) {
        if (fscanf(input_file, "%d%c", &x, &del) != 2) {
            i--;
            break;
        }
        in_data[i][j] = x;
        if ( del == '\n') {
            i++;
            j =0;
            continue;
        }
        j++;
        cols = j > cols ? j : cols;
        x = 0;
    }
    blah(in_data, 0, 0, i, cols);
}

当我使用具有 10*10 整数的输入文件运行此程序时,我在 main 中的 blah 函数调用处遇到分段错误。我也无法使用 gdb 收集有关分段错误的任何信息,它只是说:

0x0000000000400928 in blah (a=Cannot access memory at address 0x7ffffdbfe198) at blah.c

我在这里做错了什么?任何帮助将不胜感激。

【问题讨论】:

  • 如果崩溃原因来自 blah 函数,那为什么不放它的代码呢?
  • blah 中的哪一行导致崩溃?你在那儿做什么?您是否将a 更改为指向其他内容?
  • 崩溃发生在函数初始化之前,就在原型行。早些时候这个函数没问题,但我把它改成了一个二维数组作为参数,而不是一个双指针。我猜问题出在这个问题上,但无法确定。
  • 将其更改为采用数组数组更正确,因为您将其传递给数组数组。 H
  • 另外,你只发送 5 个参数,而希望获得 6 个参数?...

标签: c multidimensional-array static-allocation


【解决方案1】:

您将subband_t 键入为几 MB 的大型二维数组。这将需要几 MB 的堆栈内存。这是否有效是实施质量的问题。 #define MAXSAMPLES 10 的程序段错误吗?那就是你的问题了。

请注意

 while (! feof(input_file)) { ... }

从来没有工作过,也永远不会工作,因为EOF标志只在输入操作命中EOF之后设置。请参阅 comp.lang.c 常见问题解答。

【讨论】:

  • 实际上我在 blah 中声明了更多 sub_band_t 类型,因此堆栈内存不足将成为问题。非常感谢。
【解决方案2】:

你对 typedef 感到困惑: 你做到了:

typedef sample_t sub_band_t[MAXSAMPLES][MAXSAMPLES];
  • 编辑:

这里有一个类似问题的示例: Create a pointer to two-dimensional array

所以看起来typedef是正确的,它可能是在堆栈上分配了这么多内存,当你将MAXSAMPLES定义为10时它仍然seg fault吗? 也就像他说的那样,存在 feof 问题。 正如我评论的那样,您的函数看起来接收 6 个参数,而您只发送 5..

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 2018-05-04
  • 2017-04-18
  • 2013-10-04
  • 2011-01-08
相关资源
最近更新 更多