Segmentation Fault when using Linux, but not in Xc

2019-09-17 21:15发布

问题:

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

... and the error I get using 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

回答1:

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

Why the second line? That's the source of your problem. When you use malloced memory with C++ objects, objects are not initialized. Remove the second line and all should be well.



回答2:

Delete this line

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

Because malloc cannot call the string's constructor,so when you asign the line = "some string",program access the not written memory,will segmentation fault. Write the not-written memory is the most reason of the segmentation fault.