分段使用Linux时出现故障,但不在Xcode中 [英] Segmentation Fault when using Linux, but not in Xcode
问题描述
我在Linux环境中运行我的代码时遇到问题。但是,它与Xcode运行完美。我使用gdb backtrace来定位我的问题,它指向一行代码,其中我设置一个节点的entry字段(字符串)等于从文本文件(也是字符串)读取的行。我有一种感觉,我不包括东西或我包括错了的东西。我在路上我的头,因为我刚刚开始c ++本月。请帮助!
I am having issues running my code in a Linux environment. However, it runs perfectly with Xcode. I have used gdb backtrace to pin-point where my problem is and it points to a line of code where I am setting a node's "entry" field (a string) equal to a line read from a text file (also a string). I have a feeling I am not including something or I am including the wrong thing. I am in way over my head since I have just started c++ this month. Please help!
#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:
... and the error I get using gdb:
编程接收信号SIGSEGV,分段故障。
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
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
解决方案
推荐答案
temp =(node *)malloc(sizeof(node));
为什么是第二行?这是你的问题的根源。当您使用 malloc
ed内存与C ++对象时,不会初始化对象。删除第二行,一切都应该很好。
Why the second line? That's the source of your problem. When you use malloc
ed memory with C++ objects, objects are not initialized. Remove the second line and all should be well.
这篇关于分段使用Linux时出现故障,但不在Xcode中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!