【问题标题】:Segmentation fault when calling void function调用 void 函数时出现分段错误
【发布时间】:2016-11-18 17:39:52
【问题描述】:

编辑:根据要求,我已将代码包含在“ledic”中。但是,它从来没有运行过 - 任何一个,甚至没有 hello world printf 作为第一行,所以我相对确定问题永远不会出现在 init 中。

Edit2:具有讽刺意味的是,它在“ledic”函数中。看来我对此的了解比我之前想象的还要少。

我正在为我目前在 Uni 的项目写作,我周围没有人能弄清楚这个分段错误。它应该非常简单,因此感谢您的帮助。

代码如下:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void ledic(FILE *fp){

    printf("Hello world\n");

    int len;
    int j, i, k;
    char palavra[30];
    char dictionary[30][10000][30];
    int VecOcorrencias[30];


    for (j=0; j<30; j++)
    VecOcorrencias[j]=0;

    printf("Hello world\n");

    while ( fscanf(fp, "%s", palavra) == 1 ) {

        len = strlen(palavra);
        k = VecOcorrencias[len];
        strcpy (dictionary[len][k], palavra);
        VecOcorrencias[len]++;
    }
for (i=0; i<1000; i++)
printf("%s %d\n", dictionary[5][i], VecOcorrencias[5]);
}

}

FILE *OpenFile( char *nome, char *mode){

FILE *fp;
fp = fopen (nome, mode);
if( fp == NULL){
    printf(" Cant open file\n");
    exit(1);
}

return (fp);
}

int main( int argc, char *argv[]){

FILE * fp;

fp = OpenFile( argv[1], "r");

ledic(fp);

return(0);

}

代码在进入void ledic(FILE *fp) 函数时中断,并说它无法访问引用的内存(我想是*fp)。

我终其一生都无法弄清楚原因。有什么想法吗?

【问题讨论】:

  • ledic 函数中的代码是什么?请在您的问题中包含此内容。
  • 这可能是您在ledic() 中所做的事情有问题。你能发布ledic()的代码吗?最好是minimal reproducible example
  • 问题很可能出在您未显示的ledic 函数中...在我的计算机上,您发布的代码可以正常工作。
  • 请试试这个:char dictionary[30][10000][30]; -> static char dictionary[30][10000][30]; 并告诉我们问题是否消失。根据您告诉我们的内容,我们会给出准确的答案。
  • @aqueiro 与您的问题无关,但您确实应该正确格式化您的代码。

标签: c pointers segmentation-fault


【解决方案1】:

声明 char dictionary[30][10000][30]; 创建一个 9Mb 变量 30*30*1000 = 9'000'000。由于它是一个局部变量,它是在堆栈上创建的,典型 Linux 机器上的默认堆栈大小只有 8Mb(在 Windows 上甚至只有 1Mb)。

如果您将其声明为static,则该变量不在堆栈上,因此它可能占用比堆栈大小更多的内存。

有关static 关键字的更多详细信息,请参阅this SO article

【讨论】:

  • 非常感谢您的回答以及上下文和阅读!
猜你喜欢
  • 2011-01-08
  • 1970-01-01
  • 2018-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多