Segmentation fault on set assignment

Jan 15, 2020 at 1:41pm
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
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
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
Jan 15, 2020 at 2:28pm
Better C++ usage would be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <set>
#include <utility>
#include <memory>

struct Node
{
        std::pair<int, int> cr;
        std::set<std::pair<int, int>> mem;
        int cost;
        bool changeX;
};

std::unique_ptr<Node> gn()
{
    return std::make_unique<Node>();
}

int main()
{
    std::unique_ptr<Node> myNode = gn();
    return 0;
}
Jan 15, 2020 at 3:05pm
Thanks everyone. I changed the struct Node to class Node..
Jan 15, 2020 at 3:17pm
I changed the struct Node to class Node..


I hope you did something to gn() like @Ganado or I suggested, because simply changing struct Node to class Node will do absolutely nothing.
Jan 16, 2020 at 9:07pm
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.
Topic archived. No new replies allowed.