-5

I have code that dynamically allocates a a struct containing an std::map. This works fine on Mac and Linux but aborts the program on Windows (compiled with VC 2017). Any idea why this would be?

Partial struct definition:

typedef struct trie_node_temporary_struct {
    ...
    std::map<char, struct trie_node_temporary_struct*> child_node_map;
} trie_node_temporary_struct;

In the function:

*node = (struct trie_node_temporary_struct*)malloc(sizeof(struct trie_node_temporary_struct));
if (*node == NULL)
{
    ...
}
memset(*node, 0, sizeof(struct trie_node_temporary_struct));

// Initialize map
(*node)->child_node_map = std::map<char, struct trie_node_temporary_struct*>(); // <-- aborts here
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Jason
  • 531
  • 6
  • 19
  • 3
    Using `memset` on non-trivial object is really bad! If you need to initialize an object, make sure it has a constructor that does the *proper* initialization. However, considering that you use `malloc`, the constructor won't even be called! I suggest you take a few steps back, [get a couple of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282), unlearn your C, and start over learning C++ properly. – Some programmer dude Jan 11 '19 at 14:07
  • Using `typedef struct {...} ;` and `struct ...` are unnecessary in C++, they are carried over from C. Just use `struct {...};` and ` ...` instead, respectively. – Remy Lebeau Jan 11 '19 at 23:37
  • Removing memset didn't fix it, but converting the struct to a class and using new instead of malloc did. – Jason Jan 12 '19 at 15:23

1 Answers1

2

Your code looks like a weird mixture of C and C++. You are using malloc to allocate dynamic memory, which does not invoke C++ objects' constructors. You should use new/delete (or even better, smart pointers) if you want to dynamically allocate memory.

Any idea why this would be?

The reason why your code doesn't work is likely the fact that constructors are not invoked. I suggest reading a good C++ book (see The Definitive C++ Book Guide and List).

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416