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

Segmentation Fault when using Linux, but not in Xcode

本文关键字:Xcode 但在 错误 Linux 分段 使用      更新时间:2023-10-16

我在 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

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

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

删除此行

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

因为malloc不能调用字符串的构造函数,所以当你分配行="某个字符串"时,程序访问未写入的内存,会出现分段错误。写入未写入的内存是分段错误的最主要原因。

相关文章: