-2

I've been advised that using malloc in a c++ program shouldn't be done. How can I convert this to a non-malloc code? Thank you!

https://www.geeksforgeeks.org/union-find-algorithm-set-2-union-by-rank/

Bel
  • 45
  • 7
  • In C++ you should use `new` operator instead of `malloc`. E.g. `(struct Edge*) malloc( graph->E * sizeof( struct Edge ) ); ` should be `new Edge[graph->E];`. – Leśny Rumcajs May 27 '19 at 20:21
  • Even better would be to use `std::unique_ptr` or other smart pointer, but I think it's better to understand how `new` works at first. – Leśny Rumcajs May 27 '19 at 20:26
  • Thank you so much! This solved my problem. However since I want to have a malloc-free code, how can I also convert this bit of code using new: int *parent = (int*) malloc( graph->V * sizeof(int) ); – Bel May 27 '19 at 21:38
  • Since you're allocating space for an `int` you need to have `new int[graph->V]`. – Leśny Rumcajs May 27 '19 at 22:15
  • Ohh I understand now. Thanks so much again :) My code finally worked. – Bel May 27 '19 at 23:01
  • You're welcome. I converted this to an answer. – Leśny Rumcajs May 28 '19 at 08:46

1 Answers1

1

In C++ you should use new operator instead of malloc. E.g. (struct Edge*) malloc( graph->E * sizeof( struct Edge ) ); should be new Edge[graph->E];. It reduces the boilerplate and makes code less error-prone.

Don't forget to use delete or delete[] instead of free. Otherwise the behaviour is undefined.

Leśny Rumcajs
  • 2,259
  • 2
  • 17
  • 33