What's wrong with using malloc?


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?


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));


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.


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.