C++ 程序收到信号SIGSEGV,分段错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5856628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:03:24  来源:igfitidea点击:

Program received signal SIGSEGV, Segmentation fault

c++signalssegmentation-fault

提问by falconmick

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

好的......我正在扯掉我的头发......当我将一个名为“name”的字符串传递给内容为“joel”时为什么会出现分段错误

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.

顺便说一句...函数调用是由一个孩子,虽然我不明白这会如何导致问题。

回答by mgiuca

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

如果您使用的是 Linux,请尝试运行valgrind。您只需使用-g(使用 gcc)编译,然后valgrind在前面运行您的程序:

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

与 GCC 解决方案不同,它会告诉您何时发生段错误,而 valgrind 通常会告诉您第一次发生内存损坏的确切时间,因此您可以更接近问题的根源。

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

附注。它与“flint”押韵,而不是“find”。

回答by sehe

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
  • 显示的错误,索引是基于 0 的,所以你需要 for (i=0; i<10; i++)
  • 如果数组是动态分配的,但索引仍然越界

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

自我注意:我为什么要这样做/我不是通灵者?

回答by user3849792

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.

问题必须出在方法调用中。