ForumsProgramming ForumC++ Help: Segmentation Fault

3 3457
Kevin4762
offline
Kevin4762
2,420 posts
Nomad

//Kevin Pomerantz CISC181010 Lab020 Fei Che
//The program creates structures based on the top 250
//movies as determined by imdb.com.

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

struct Movie{
char* name;
int year;
double rating;
};

void printMovie(Movie* mptr);
Movie* makeMovie(ifstream* inFile);

int main(){

Movie* list[10];
char path[100];
ifstream inFile;

cout << "Enter a file name: ";
cin >> path;

inFile.open(path);

if(inFile.fail()){
cout << path << " : File not found.\
";
return -1;
}

for(int i = 0; i < 10 && !inFile.eof(); i++){
list[i] = makeMovie(&inFile);
cout << 1 << endl;
}

return 0;
}

void printMovie(Movie* mptr){

cout << "Name: " << mptr->name << endl
<< "Year: " << mptr->year << endl
<< "Rating: " << mptr->rating << endl
<< endl;

return;
}

Movie* makeMovie(ifstream* inFile){

char tempName[30];
char* name;
int year;
double rate;

*inFile >> tempName;
*inFile >> year;
*inFile >> rate;

name = new char[strlen(tempName)];
strcpy(name, tempName);

Movie* aMovie = new Movie;
strcpy(aMovie->name, name);
aMovie->year = year;
aMovie->rating = rate;

return aMovie;
}

  • 3 Replies
Kevin4762
offline
Kevin4762
2,420 posts
Nomad

I'm getting a segmentation fault when I run this. It compiles fine, and it reads from the file fine, it even prints a 0 when it runs, so I know that it has something to do with my list array.

I need to figure out what is making this segmentation fault. Any help is appreciated.

File that it's reading from:

Shawshank 1994 9.1
Godfather 1972 9.1
Godfather2 1974 9.0
Ilbuono 1966 8.9
Fiction 1994 8.9
Schindler 1993 8.8
Angry 1957 8.8
Cuckoo 1975 8.8
Empire 1980 8.8
DarkKnight 2008 8.8
ReturnKing 2003 8.8
StarWars 1977 8.8
Casablanca 1942 8.7
Goodfellas 1990 8.7
Shichinin 1954 8.7
FightClub 1999 8.7
Cidade 2002 8.7
Fellowship 2001 8.7
Raiders 1981 8.7
RearWindow 1954 8.7
Erasmus_Darwin
offline
Erasmus_Darwin
59 posts
Nomad

It's crashing in makeMovie. There are actually two problems in there. The first is this:

name = new char[strlen(tempName)];

You need to add 1 to the number of characters you allocate because strlen doesn't count the terminating null character. That'll cause problems, but that isn't what's causing your segfault in this case.

The main problem is this:

strcpy(aMovie->name, name);

Since aMovie->name was never initialized, you can't copy a string there. You probably wanted to just copy the pointer:

aMovie->name = name;

Kevin4762
offline
Kevin4762
2,420 posts
Nomad

Thanks. I thought I found out specifically where it seg faults:

In makeMovie:

Code:
Movie* aMovie = new Movie;

It runs makeMovie fine the first time through the loop, and then the second time through it seg faults when it attempts to create space on the heap for the new Movie.

Thanks man.

Showing 1-3 of 3