c++ - 使用 Linux 时出现段错误,但在 Xcode 中没有

标签 c++ linux xcode linked-list nodes

我在 Linux 环境中运行代码时遇到问题。但是,它与 Xcode 完美运行。我使用 gdb backtrace 来查明我的问题所在,它指向一行代码,我在其中设置节点的“入口”字段(一个字符串)等于从文本文件(也是一个字符串)读取的一行。我有一种感觉,我没有包含某些东西,或者我包含了错误的东西。自从我这个月刚开始使用 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

最佳答案

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

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

关于c++ - 使用 Linux 时出现段错误,但在 Xcode 中没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27199827/

相关文章:

可空引用的 C++ 惯用方式

c++ - TUN/TAP 上的 C 编译器错误

c++ - 来自 QT QWidget 的 X11 小部件

xcode - 旧版本的应用程序出现在模拟器中

objective-c - 两个 NSDate 的问题

c++ - 调用非虚拟成员时消除基类歧义

C++构造函数线程安全

Swift Navigation Controller 轻扫以返回任何地方

c++ - 段错误 : 11 and malloc errors in C++ code

c++ - 解决 GNU 中重新声明的链接器错误