user2350590
user2350590

Reputation: 1

Segmentation Fault when accessing a struct

I have a header file where I define methods. I am ultimately trying to implement a doubly linked list to store data of pairs. this is cont.h

template <class Key, class T> class storage;

template < class Key, class T, class Compare = std::less<Key> > 
class cont{
    private:
        storage <Key, T> data;
    public:
        typedef size_t size_type;
        typedef Key key_type;
        typedef T mapped_type;

        //default constructor
        cont(){}

        cont(key_type k, mapped_type m)
        {
            std::pair<Key, T> x = std::make_pair(k,m);
            data.begin_list(x);

            //std::pair<Key, T> a = std::make_pair(k,m);
            //data.push(a);
        }



};

template <class Key, class T>
struct node
{
    node *prev, *next;
    std::pair<Key, T> node_data;
};

template <class Key, class T>
class storage{
    private:
        node <Key, T> *head;
        node <Key, T> *tail;
        node <Key, T> *curr;
        int size;
    public:
        //default ctor
        storage(){}

        void begin_list(std::pair <Key, T> h)
        {
            size=1;
                    //bottom two lines induce segmentation fault
            //head->node_data=h;
            //head->prev=NULL;

        }

};

main.cc will look like this:

#include "cont.h"
int main() {
    cont<double, int> s(6.6, 3);
}

I don't understand why I get segfault. Should I be dynamically allocating memory for each node?

Upvotes: 0

Views: 585

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126542

Well, head has not been initialized by the time begin_list gets executed, so dereferencing it gives you undefined behavior:

    void begin_list(std::pair <Key, T> h)
    {
        size=1;

        head->node_data=h; // <= DEREFERENCING head WITHOUT HAVING INITIALIZED IT
        head->prev=NULL; // <== SAME HERE
    }

Here you probably meant to dynamically allocate an object of type node in the constructor of storage, assigning the result of the corresponding new expression to head (and then making tail and curr point to the same object.

However, please consider not using new, delete, and raw pointers for memory management purposes. Prefer using smart pointers to express ownership.

Upvotes: 1

Related Questions