SIGSEGV program signal, segmentation error

Ok ... I tore my hair ... Why do I get segmentation phagos when I pass a line called "name" with the contents of "joel" to

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 made by the child, although I don't see how this might cause the problem.

+7
source share
3 answers

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

 $ valgrind myprogram 

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

PS. It rhymes with โ€œflint,โ€ not โ€œfinding."

+17
source

You are probably looking for a rogue index. Pure guess, you have something like this, perhaps:

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

The problem may be:

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

In fact, there may be hundreds of other reasons, but since I do not have your code, this is my attempt to guess the most plausible errors;)

(Pay attention to yourself: why am I doing this / am I not psychic?)

+1
source

The code looks great, except that you copy the line all the time. Instead

 void setName(string newName); 

it should be

 void setName(const string& newName); 

The problem should be in the method call.

-2
source

All Articles