Jan 15, 2020 at 1:41pm UTC
typedef struct {
pair<int,int> cr;
set<pair<int, int>> mem;
int cost;
bool changeX;
}Node;
Node* gn() {
return (Node *)malloc(sizeof(Node));
}
int minimumMoves(vector<string> grid, int startX, int startY, int goalX, int goalY) {
queue<Node* > q;
Node* tn;
int n = grid.size();
int minStepCount = n*n+100;
Node* start = gn();
start->cr = make_pair(startX, startY);
start->cost = 0;
start->changeX = true;
set <pair<int, int>> s;
s.insert(make_pair(startX, startY));
start->mem = s; // Segmentation error
q.push(start);
....
}
With gdb I see line `start->mem = s` gives error
Program received signal SIGSEGV, Segmentation fault.
0x0000000000404810 in std::_Rb_tree<std::pair<int, int>, std::pair<int, int>, std
::_Identity<std::pair<int, int> >, std::less<std::pair<int, int> >, std::allocato
r<std::pair<int, int> > >::_Reuse_or_alloc_node::_Reuse_or_alloc_node (
this=0x7fffffffe7b0, __t=...) at /usr/include/c++/6/bits/stl_tree.h:386
386 if (_M_nodes->_M_left)
Jan 15, 2020 at 2:18pm UTC
std::set is a C++ class. If you use C memory allocation to allocate space for it, the constructor won't be invoked, so you don't have a working, initialised std::set object, just some uninitialised memory.
You need to use C++ memory allocation to create your object.
Jan 15, 2020 at 2:25pm UTC
You're writing C++, so why are you using malloc instead of new?
If you use new, I bet the segfault will go away.
1 2 3
Node* gn() {
return new Node;
}
Last edited on Jan 15, 2020 at 2:25pm UTC
Jan 15, 2020 at 3:05pm UTC
Thanks everyone. I changed the struct Node to class Node..
Jan 16, 2020 at 9:07pm UTC
Without any access specifiers changing the struct
to a class
would make all the member variables private
, making the situation much worse ….
I fail to see how the OP can say that it would make it work now.
Even with the public specifier, it would make no difference, as doug4 says.