What's wrong with using malloc?


#1

Wasted 1 hour of debugging segmentation fault, which was because of using malloc to create a new node rather than the constructor.
Can anyone explain?


#2

They already provide us with “new UndirectedGraphNode(data)”.
and if you wanna use malloc you can certainly do that with correct syntax.

UndirectedGraphNode* temp=(UndirectedGraphNode*)malloc(sizeof(UndirectedGraphNode));


#3

Agreed. even after using correct malloc syntax, it is giving segmentation fault.
We have to use new keyword for solution to run. I would be greatful if somebody can help me why this is the case.


#4

The problem with malloc is that the neighbors vector constructor is not run.
Since the memory returned by malloc contains arbitrary data, this very likely means that the neighbors vector is broken. You might get by if you memset everything to 0, but this depends on the vector implementation.
Calling “new” is the way to go.