c++ - Initializing a complex object. Error when I don't? -
i can't seem figure out why program crashes every time node object. , can't make progress until working...
my problem is: whenever try "set data" on node x, access violation error. before getting runtime failure #3 not initializing variable. initialize null, , still error. previous node classes never gave me error, kinda stumped. appreciated!
here's code:
node class:
#ifndef node #define node template <typename t> class node { public: node(); node(t data); void setdata(t data); private: t m_data; }; template <typename t> node<t>::node() { } template <typename t> void node<t>::setdata(t data) { m_data = data; } #endif
main:
#include <iostream> #include <crtdbg.h> #include "node.h" #define _crtdbg_map_alloc int main() { _crtsetdbgflag(_crtdbg_alloc_mem_df | _crtdbg_leak_check_df); node<int> * x = nullptr; x->setdata(20); return 0; }
the weird thing is, whenever "new" allocate new node, problem doesn't occur.. in advance.
you dereferencing null pointer value results in undefined behavior. need create instance of node<int>
, assign x
so
node<int> * x = new node<int>(); x->setdata(20);
or use automatic storage duration , declare x
value.
node<int> x; x.setdata(20);
Comments
Post a Comment