简体   繁体   中英

Program received signal SIGSEGV, Segmentation fault

Ok... I am ripping my hair out... Why am I getting segmentation fauls 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;

};

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

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".

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? )

The code looks fine apart from the fact that you copying string all the time. Instead of

void setName(string newName);

should be

void setName(const string& newName);

The issue must be in the method invocation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM