【发布时间】: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