class graph
{
int v;
list *adj;
void dfsutil(int v,bool visited []);
public:
graph(int v)
{
this->v=v;
//adj =
You did not create an array of std::list
objects when you used malloc
. All malloc
does is allocate memory from the heap -- no objects are created. Thus attempting to use your std::list
's as if they are created correctly will result in undefined behavior.
You should use a container such as std::vector
to store your list objects:
#include <vector>
#include <list>
class graph
{
int v;
std::vector<std::list<int>> adj;
void dfsutil(int v,bool visited []);
public:
graph(int num) : v(num), adj(num) {}
void addedge(int v,int w);
void dfs(int v);
};
Note there is no need to allocate memory. The rest of your code should stay the same, since vector
has an overloaded operator []
to access the items.