Search code examples
c++stlsegmentation-faultmallocnew-operator

Using Malloc to allocate memory to STL list?


I am trying to allocate memory to stl list using malloc. I works fine with new as below:

typedef pair<int, int> iPair;
list< pair<int, int> > *adj;
adj = new list<iPair> [V];

But throws segmentation fault if I use malloc instead of new.

adj=(list<iPair> *)malloc(sizeof(list<iPair>)*V);

Why malloc cannot be used to allocate memory to STL containers?


Solution

  • Because malloc comes from C and C has no idea of classes and thus no concept of constructors. new allocates the memory and calls the appropriate constructor, malloc only allocates the memory.