URGENT! What is wrong with this code?

I am doing a project and the following is one part of my code.

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

#define NO_VOTERS 2977
#define NO_MOVIES 1627

struct Person {
  short id;
/*  char zipcode[6];  */
  short age;
  char gender;
};

struct Movie {
/*  char theatre_status[8];
  char video_status[8]; */
  short id;
  short action;
  short animation;
  short art_foreign;
  short classic;
  short comedy;
  short drama;
  short family;
  short horror;
  short romance;
  short thriller;
};

struct Vote {
  short person_id;
  short movie_id[NO_MOVIES];
  float score[NO_MOVIES];
};

int main(int argc, char** argv) {
  FILE *infile1, *infile2, *infile3, *outfile;
  struct Person voter[NO_VOTERS];
  struct Movie movie[NO_MOVIES];
  struct Vote vote[NO_VOTERS];
  short last_read_person_id, person_id, movie_id;
  float score;
  short notfound;
  short movietype[10];

  int i, j, k, m;
  float t;

  fprintf(stderr, "Opening file...\n");
  if ((infile1=fopen("person_simplified.txt", "r"))==NULL) {
    fprintf(stderr, "Error opening file: person_simplified.txt\n");
    exit(-1);
  }  if ((infile2=fopen("movie_simplified.txt", "r"))==NULL) {
    fprintf(stderr, "Error opening file: movie.txt\n");
    exit(-1);
  }
  if ((infile3=fopen("vote1_simplified.txt", "r"))==NULL) {
    fprintf(stderr, "Error opening file: vote1.txt\n");
    exit(-1);
  }
  if ((outfile=fopen("vote.nominal.arff", "w"))==NULL) {
    fprintf(stderr, "Error opening file: vote1.txt\n");
    exit(-1);
  }
  fprintf(stdout, "Initialization...\n");
  for (i=0; i<NO_VOTERS; i++) {
    for (j=0; j<NO_MOVIES; j++) {
      vote[i].movie_id[j]=-1;
      vote[i].score[j]=-1;
    }
  }

  return 0;
}

I am getting "Segmentation fault" when getting into the for loop. Can someone helps me?
LVL 16
Peter KwanAsked:
Who is Participating?
 
nebekerConnect With a Mentor Commented:
When I tried your program, I got a stack overflow exception.  Essentially, the "automatic" variables you're declaring at the beginning of your program are being allocated on the stack (instead of the heap), and they're just too big.

The variable: "struct Vote vote[NO_VOTERS];" alone is around 9 MB in size....

You shouldn't EVER declare large variables on the stack - always get them on the heap (via malloc).  If you don't believe me, just delete ALL of your code after the statement:

 float t;

and put this:

 printf( "Hello!\n" );
 exit(0);

and you'll still get the segmentation fault.

Reorganize the larger variables:

 struct Person voter[NO_VOTERS];
 struct Movie movie[NO_MOVIES];
 struct Vote vote[NO_VOTERS];

to be pointers, and then allocate their storage with malloc, and the problem will go away.
0
 
Peter KwanAuthor Commented:
Thanks for your comment. I am going to try out your method and tell you the results later.
0
All Courses

From novice to tech pro — start learning today.