c++ - Segmentation Fault when accessing a struct -
i have header file define methods. trying implement doubly linked list store data of pairs. 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> = 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 2 lines induce segmentation fault //head->node_data=h; //head->prev=null; } };
main.cc this:
#include "cont.h" int main() { cont<double, int> s(6.6, 3); }
i don't understand why segfault. should dynamically allocating memory each node?
well, head
has not been initialized time begin_list
gets executed, dereferencing gives undefined behavior:
void begin_list(std::pair <key, t> h) { size=1; head->node_data=h; // <= dereferencing head without having initialized head->prev=null; // <== same here }
here meant dynamically allocate object of type node
in constructor of storage
, assigning result of corresponding new
expression head
(and making tail
, curr
point same object.
however, please consider not using new
, delete
, , raw pointers memory management purposes. prefer using smart pointers express ownership.
Comments
Post a Comment