0

I have a struct that looks like this:

struct Vertex
{
    int state;
    int degree;
    int *neighbor;
    unordered_set<int> neighbors_set;
};

I am allocating a bunch of these structs like this:

vertex = (Vertex *)malloc(v_n * sizeof(Vertex));

but when I try to add an item to the neighbour_set of a particular vertex like this:

vertex[x].neighbors_set.insert(1);

the program crashes.

Does anyone have an idea how to fix this?

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
Daniel
  • 83
  • 6
  • [Please see this discussion on why not to cast the return value of malloc() and family in C..](https://stackoverflow.com/q/605845/2173917) – Sourav Ghosh Oct 07 '20 at 07:16
  • Please show a [mcve]. – Sourav Ghosh Oct 07 '20 at 07:17
  • 1
    Don't mix C++ and C API. – Tanveer Badar Oct 07 '20 at 07:20
  • `unordered_set` is not `c`, in general tagging a question with both `c` and `c++` is most of the time wrong. – t.niese Oct 07 '20 at 07:20
  • @t.niese A question asking about using malloc() for allocating a C++ struct seems adequatly tagged both C and C++. One of the rare cases I could actually agree with both tags. Not starting a retagging war here, I want to convince you. – Yunnosch Oct 07 '20 at 07:22
  • 2
    @Yunnosch I disagree. Because of unordered set, this is a c++ question. The real answer to 99.9% of why malloc doesn't work in a c++ question is 'don't use malloc'. This answer would not fly in a question marked for c. – Fantastic Mr Fox Oct 07 '20 at 07:23
  • Fair enough. @t.niese Adding the malloc detail to title is however OK for you I hope, considerung it C or not. – Yunnosch Oct 07 '20 at 07:23
  • .The problem may come from the value of x : is it to big compared to the number of allocated records (v_n) ? . The problem may also come from the unordered_set template. What is doing the insert operation ? – Rachid K. Oct 07 '20 at 07:33
  • 2
    @RachidK. insert operation is using a C++ object which was not constructed – Slava Oct 07 '20 at 08:14

2 Answers2

3

You cannot use malloc() to allocate C++ classes on heap and expect everything to work. It has not called the constructor for that unordered_set like new Vertex would have.

You can either change it to using new Vertex or at least use the placement new option (which will be like new(vertext) Vertex) to properly initialize the object.

P.S.: I missed that you are allocating multiple objects. Either use array new option or better yet, eschew all manual memory management and switch to std::vector<Vertex>.

Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
1

You clearly know about the std::unordered_set, so the best advice for solving this problem is to use the c++ lib correctly. In this instance, it seems like you want a vector of your struct with length v_n, so, make a std::vector:

std::vector<Vertex> vertices(v_n);

Your access will look the same, and this time it should work.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175