aqueiro aqueiro - 2 years ago 83
C Question

Segmentation fault when calling void function

Edit: as requested I've included the code in 'ledic'. However, it never ran - any of it, not even a hello world printf as first line, so I am relatively sure the problem would never be withinit.

Edit2: ironically enough, it was within the 'ledic' function. Looks like I understand even less about this than I previously thought.

I am writing for my current project at Uni and no one around me can figure out this segmentation fault. It should be pretty straightforward so I appreciate your help.

Code as follows:

#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++)

printf("Hello world\n");

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

len = strlen(palavra);
k = VecOcorrencias[len];
strcpy (dictionary[len][k], palavra);
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");

return (fp);

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

FILE * fp;

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




The code breaks when it enters the
void ledic(FILE *fp)
function, and says it cannot access the referenced memory (I suppose *fp).

I cannot for the life of me figure out why. Any thoughts?

Answer Source

The declaration char dictionary[30][10000][30]; creates a 9Mb variable 30*30*1000 = 9'000'000. As it is a local variable it is created on the stack and the default stack size on a typical Linux machine is only 8Mb (on Windows it's even only 1Mb).

If you declare it as static, the variable is not on the stack and therefore it can take more memory than the stacksize.

See this SO article for more details on the static keyword.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download