【问题标题】:Segmentation Fault when using Linux, but not in Xcode使用 Linux 时出现分段错误,但在 Xcode 中没有
【发布时间】:2014-11-29 07:06:09
【问题描述】:

我在 Linux 环境中运行我的代码时遇到问题。但是,它可以完美地与 Xcode 一起运行。我已经使用 gdb 回溯来确定我的问题所在,它指向我将节点的“条目”字段(字符串)设置为等于从文本文件(也是字符串)读取的行的代码行。我有一种感觉,我没有包含某些东西,或者我包含了错误的东西。自从我这个月才开始使用 c++ 以来,我一直处于不知所措的状态。请帮忙!

#include <iostream>
#include <fstream>      // for reading dictionary.txt
#include <cstdlib>      // for rand() and srand()
#include <time.h>       // for time
#include <string>       // for string

using namespace std;

...

struct node
{
    string entry;       // stores the dictionary entry
    node *next;         // stores pointer to next node in list
};
node *head = NULL;

...

ifstream dictionary;
dictionary.open(filename);
string line;
if (dictionary.is_open())
{
    while (getline(dictionary,line))
    {
        if (head == NULL)
        {
            node *temp = new node;
            temp = (node*)malloc(sizeof(node));
            temp->entry = line;    // this is where I segfault according to backtrace
            temp->next = NULL;
            head = temp;
        } // if first entry

... 以及我使用 gdb 得到的错误:

Program received signal SIGSEGV, Segmentation fault. 0x0000003ce2a9d588 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::assign(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) () from /usr/lib64/libstdc++.so.6

【问题讨论】:

  • 你应该使用new而不是malloc。
  • 这是段错误,因为 malloc 没有调用字符串构造函数。只需按照 R Sahu 的建议删除带有 malloc 的行

标签: c++ linux xcode linked-list nodes


【解决方案1】:
        node *temp = new node;
        temp = (node*)malloc(sizeof(node));

为什么是第二行?这就是你问题的根源。当您将 malloced 内存与 C++ 对象一起使用时,对象不会被初始化。删除第二行,一切都会好起来的。

【讨论】:

  • 啊,谢谢。你知道为什么这会在 Xcode 中毫无问题地运行吗?只是好奇。
  • @user1655752,我对 Xcode 没有任何经验。我无法评论为什么代码在 Xcode 下可以正常运行。
【解决方案2】:

删除这一行

temp = (node*)malloc(sizeof(node))

由于malloc不能调用字符串的构造函数,所以当你指定line = "some string"时,程序访问未写入的内存,会出现段错误。 写入未写入的内存是导致分段错误的最主要原因。

【讨论】:

    猜你喜欢
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多