使用 Linux 时出现分段错误,但在 Xcode 中没有
Segmentation Fault when using Linux, but not in Xcode
我在 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不能调用字符串的构造函数,所以当你分配行="某个字符串"时,程序访问未写入的内存,会出现分段错误。写入未写入的内存是分段错误的最主要原因。
相关文章:
- 代码在main()中运行,但在函数中出现错误
- 链接阶段在Ubuntu上失败,但在MacOS上失败
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- "Unable to open file libc++abi.dylib" .程序生成,但在运行时崩溃。使用 xcode 10.1 (10B61)
- 用警告在G 上编译代码,但在Clang3.1(Xcode 4.3.3)上给出了相同代码的错误
- 在 Xcode 6 中运行 cpp-netlib - 编译但在运行时崩溃
- clang++ 3.1,但在Lion Xcode 4.3.3上没有“cxx_lambdas”
- 在 .h 中声明名称,但在 Xcode 中以.cpp形式报告未声明
- boost::mutex 在 Visual Studio 中支持 try_lock_for,但在 Xcode 中不支持
- 使用 Linux 时出现分段错误,但在 Xcode 中没有
- 在Xcode中传递指针时出错,但在窗口上的代码块中有效
- Eclipse ADT "undefined reference to (custom class)",但在 Xcode 中工作正常(使用 Cocos2dx)
- 代码在xcode中运行良好,但在命令行中出错
- GCC 4.2.2中的编译错误.但在Xcode 6.4中工作
- c++程序在命令行上工作,但在Xcode上失败
- 从txt文件中读取数据,在Visual Studio中工作,但在Xcode中失败
- 代码在 g++ 中运行良好,但在 Xcode 中无法运行 - 找不到文件
- c++标准库在.mm文件中找到,但在.h文件中找不到(Xcode 4.5 LLVM GCC 4.2)