Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,728 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,323 people online right now. Registration is fast and FREE... Join Now!




Segmentation Fault (core dumped)

 
Reply to this topicStart new topic

Segmentation Fault (core dumped), I get a seg fault when I run my program

jeisma
7 Feb, 2007 - 03:54 PM
Post #1

New D.I.C Head
*

Joined: 14 Sep, 2006
Posts: 17


My Contributions
I get a seg fault when I run my program and I narrowed it down to where it is..

CODE

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


class SongDatabase
{
public:
  string GetArtist(string Artist);
  string GetSong(string Song);
  string GetGenre(string Genre);
  float GetPrice(float Price);
  int GetCount(int PurchaseCount);
  void purchaseSong();
private:
  string artist;
  string song;
  string genre;
  float price;
  int purchaseCount;
};

string SongDatabase::GetArtist(string Artist)
{
  artist = Artist;
}

string SongDatabase::GetSong(string Song)
{
  song = Song;
}

string SongDatabase::GetGenre(string Genre)
{
  genre = Genre;
}

float SongDatabase::GetPrice(float Price)
{
  price = Price;
}

int SongDatabase::GetCount(int PurchaseCount)
{
  purchaseCount = PurchaseCount;
}

int main()
{

  int max = 200;
  SongDatabase Song[max];
  ifstream infile;
  ofstream outfile;

  string songArray[5];
;
  const char* str_price;
  const char* str_count;
  float price;
  int count;

  infile.open("songlist.txt");

  int a = 0;

  while(!infile.eof())
    {
      for (int i = 0; i < 5; i++)
    {
      getline(infile, songArray[i], ',');
    }

      str_price = songArray[3].c_str();
      str_count = songArray[4].c_str();

      price = atof(str_price);
      count = atoi(str_count);
      
      /* These next 3 lines cause the seg fault..*/
      //Song[a].GetArtist(songArray[0]);
      //Song[a].GetSong(songArray[1]);
      //Song[a].GetGenre(songArray[2]);
      Song[a].GetPrice(price);
      Song[a].GetCount(count);
      a++;
    }

  infile.close();


}



The 3 lines commented out cause a seg fault and I don't know why. When I uncomment any one line, it will cause a seg fault. At first It hought it had to do with the array variable, but I determined that wasn't it. So, I'm figuring it has to do with my class SongDatabase functions, or maybe because they're string data types that I'm passing through? I don't know. I'm clueless.
User is offlineProfile CardPM
+Quote Post

ByteWyse
RE: Segmentation Fault (core Dumped)
7 Feb, 2007 - 05:31 PM
Post #2

New D.I.C Head
*

Joined: 2 Jan, 2007
Posts: 41


My Contributions
First, you define several methods with return types, and when you implement them, you have no return statements.
CODE

string SongDatabase::GetGenre(string Genre)
{
  genre = Genre;
}


Second, while it's not a functional issue, these methods have names containing "Get", but they appear to be mutators rather than accessors. Should these be renamed using "Set"?

Third, when defining non-POD types as parameters, prefer passing by pointer or reference and especially pointer-to-const or reference-to-const.

Fourth, your main doesn't have a return statement.

Once I corrected these issues, it seems to work fine.

CODE

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


class SongDatabase
{
public:
  void SetArtist(const string &Artist);
  void SetSong(const string &Song);
  void SetGenre(const string &Genre);
  void SetPrice(float Price);
  void SetCount(int PurchaseCount);
  void purchaseSong();
private:
  string artist;
  string song;
  string genre;
  float price;
  int purchaseCount;
};

void SongDatabase::SetArtist(const string &Artist)
{
  artist = Artist;
}

void SongDatabase::SetSong(const string &Song)
{
  song = Song;
}

void SongDatabase::SetGenre(const string &Genre)
{
  genre = Genre;
}

void SongDatabase::SetPrice(float Price)
{
  price = Price;
}

void SongDatabase::SetCount(int PurchaseCount)
{
  purchaseCount = PurchaseCount;
}

int main()
{

  int max = 200;
  SongDatabase Song[max];
  ifstream infile;
  ofstream outfile;

  string songArray[5];
// Stray semicolon?
//;
  const char* str_price;
  const char* str_count;
  float price;
  int count;

  infile.open("exe/songlist.txt");
      // Added test to verify that the file opened successfully.
    if (!infile) {
          cerr << "Failed to open file\n";
          return -1;
      }    // if (!infile)

  int a = 0;

  while(!infile.eof())
    {
      // Prefer pre-increment to post-increment.
      for (int i = 0; i < 5; ++i)
    {
      getline(infile, songArray[i], ',');
    }

      str_price = songArray[3].c_str();
      str_count = songArray[4].c_str();

      price = atof(str_price);
      count = atoi(str_count);
      
      Song[a].SetArtist(songArray[0]);
      Song[a].SetSong(songArray[1]);
      Song[a].SetGenre(songArray[2]);
      Song[a].SetPrice(price);
      Song[a].SetCount(count);

      // Prefer pre-increment to post-increment.
      ++a;
    }

  infile.close();
  return 0;

}


Finally, in C you must declare all local variables in a function prior to the first code statement. Since in C++, this is no longer necessary, it is generally considered good practice to define local variables as near as practical to their first use.

CODE

int main()
{

    int max = 200;
    SongDatabase Song[max];


    ifstream infile;
    infile.open("exe/songlist.txt");
    // Added test to verify that the file opened successfully.
    if (!infile) {
          cerr << "Failed to open file\n";
          return -1;
      }    // if (!infile)

    int a = 0;

    while(!infile.eof())
    {
        string songArray[5];
        for (int i = 0; i < 5; ++i)
        {
            getline(infile, songArray[i], ',');
        }

        const char *str_price = songArray[3].c_str();
        const char *str_count = songArray[4].c_str();

        float price = atof(str_price);
        int count = atoi(str_count);
      
        Song[a].SetArtist(songArray[0]);
        Song[a].SetSong(songArray[1]);
        Song[a].SetGenre(songArray[2]);
        Song[a].SetPrice(price);
        Song[a].SetCount(count);

        // Prefer pre-increment to post-increment.
        ++a;
    }

    infile.close();
    
    return 0;

}


User is offlineProfile CardPM
+Quote Post

jeisma
RE: Segmentation Fault (core Dumped)
7 Feb, 2007 - 05:58 PM
Post #3

New D.I.C Head
*

Joined: 14 Sep, 2006
Posts: 17


My Contributions
Hey thanks a lot! That helped me so much. I sort of understood why you made my functions set instead of get, I'm still confused about why you put ampersands (&) in front of the variables ( still need a little more explaining about that). I'm also not sure exactly what made the segfault happened. Was it a combination of all of that? What happens if there's no retur 0 at the bottom of my main function?
User is offlineProfile CardPM
+Quote Post

ByteWyse
RE: Segmentation Fault (core Dumped)
7 Feb, 2007 - 08:05 PM
Post #4

New D.I.C Head
*

Joined: 2 Jan, 2007
Posts: 41


My Contributions
QUOTE(jeisma @ 7 Feb, 2007 - 06:58 PM) *

Hey thanks a lot! That helped me so much. I sort of understood why you made my functions set instead of get, I'm still confused about why you put ampersands (&) in front of the variables ( still need a little more explaining about that). I'm also not sure exactly what made the segfault happened. Was it a combination of all of that? What happens if there's no retur 0 at the bottom of my main function?


The ampersands declare the parameters to be references, otherwise the compiler will cause the strings to be passed by value, meaning that it will have to make copies, which is expensive.

The segfaults are stack errors caused when functions were declared as returning values but actually didn't.

User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 1/8/09 05:06AM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month