2

While learning BFS from geekforgeek, I notice that there is no delete adj for the new list<int> array:

 adj = new list<int>[V];

Will it cause a memory leak? For this question, I made a demo to using delete to release the memory explicitly.

#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

int main()
{
    list<int> *adj = new list<int>[3];
    cout << adj->size() << endl;

    delete adj;
}

delete operation will cause coredump. So why does deleting pointer to list cause core dump? How to release the memory by new operation?

leiyc
  • 903
  • 11
  • 23
  • 14
    You can't `delete` a pointer created by `new[]`. You need to use `delete[]`. – tkausl Sep 23 '19 at 12:09
  • 2
    "_why does deleting pointer to list_" `adj` is not a pointer to `list`, though. It's a pointer to an array of `list`s. – Algirdas Preidžius Sep 23 '19 at 12:10
  • @tkausl, yes, it is. I made a stupid mistake... Thanks – leiyc Sep 23 '19 at 12:13
  • @tkausl - you should post it as an answer – bobah Sep 23 '19 at 12:21
  • A `std::list` is a container that dynamically manages the objects that it contains. It makes very little sense to dynamically allocate a `std::list` with `new` or `new[]`. – Eljay Sep 23 '19 at 13:21
  • @Eljay: There are plenty of reasons, especially since `list` can (since C++17) be instantiated with incomplete types, allowing it to be part of a tree node. Having a variable number of `list`s in an array is also legitimate, although of course one should usually use `std::vector>` then. – Davis Herring Sep 24 '19 at 01:42

0 Answers0