falconmick
falconmick

Reputation: 89

Program received signal SIGSEGV, Segmentation fault

Why am I getting segmentation fault when I am passing a string called name with contents joel into:

void person::setName(string newName)
{
    personName = newName;
}

Header file:

class person {
public:
    int getID();
    string getName();

    void setID(int newID);
    void setName(string newName);
private:
    int personID;
    string personName;

};

The function call is by a child, although I dont see how that could cause an issue.

Upvotes: 8

Views: 68763

Answers (3)

moonchildsrj
moonchildsrj

Reputation: 1

#include <iostream>

using namespace std;

class person {
public:
    int getID();
    string getName();

    void setID(int newID);
    void setName(string newName);
private:
    int personID;
    string personName;

};

void person::setName(string newName)
{
    personName = newName;
    cout << personName << endl;
}

int main() {
  person* obj = new person();
  obj->setName("your name");
  return 0;
}

Upvotes: -1

mgiuca
mgiuca

Reputation: 21357

If you are on Linux, try running valgrind. You just compile with -g (with gcc), and then run your program with valgrind in front:

$ valgrind myprogram

Unlike the GCC solutions, which tell you when the segfault occurs, valgrind usually tells you exactly when the first memory corruption occurs, so you can catch the problem much closer to its source.

PS. It rhymes with "flint", not "find".

Upvotes: 23

sehe
sehe

Reputation: 392979

Probably, you are dereferencing a rogue pointer. By pure guesswork, have you got something like this, perhaps:

 Person persons[10];

 for (i=1; i<=10; i++)
     persons[i].setName("joel");

The problem might be:

  • the error like shown, the index is 0-based, so you need for (i=0; i<10; i++)
  • if the array is allocated dynamically, but the index is still out of bounds

There could literally be hundreds of other causes, but since I don't have your code, this is my attempt to guess most plausible errors ;)

(Note to self: why am I doing this/I'm not psychic?)

Upvotes: 2

Related Questions