1

I have created an array of vector using pointer and allocated its size using the new keyword. But when I tried to free the allocated memory, it gave me this error-

free(): invalid pointer  
Aborted (core dumped)

Here is my code,

#include "bits/stdc++.h"
using namespace std;

vector<int> *adjlist;

int main()
{
    adjlist = new vector<int>[10];    
    delete adjlist;    
    return 0;
}

The new keyword allocates in heap, so I tried to free heap memory using delete. Because, unlike stack, the heap memory won't get cleared automatically. When I used parentheses instead of square brackets, it didn't show me any error.

#include "bits/stdc++.h"
using namespace std;

vector<int> *adjlist;

int main()
{
    adjlist = new vector<int>(10);    
    delete adjlist;    
    return 0;
}

So, why the first code is getting an error but not the second. And how do I free the heap memory?

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
SI Abid
  • 11
  • 2
  • 1
    The first one creates an ***array*** which must be destroyed with `delete[]`. – Sam Varshavchik May 20 '21 at 10:46
  • You allocated an array of 10 vectors, not a vector of 10 ints – Caleth May 20 '21 at 10:47
  • frankly, you should probably pick a better source for learning. A `vector[10];` is an abdomination that maybe has some rare use-cases, but I have never seen one. I know that there are certain "tutorial" sites that promote such weird constructs, don't follow them – 463035818_is_not_an_ai May 20 '21 at 10:47
  • 1
    See also: [c++ - Why should I not #include ? - Stack Overflow](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [c++ - Why is "using namespace std;" considered bad practice? - Stack Overflow](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – MikeCAT May 20 '21 at 10:47
  • Aside: You should not use new. `std::vector adjlist(10);` gives you a vector of 10 ints – Caleth May 20 '21 at 10:48
  • 1
    Or if you really want 10 `std::vector`s, `std::array, 10> adjlist;` or `std::vector> adjlist(10);` – Caleth May 20 '21 at 10:51
  • Thank you @SamVarshavchik. It solved my issue. – SI Abid May 20 '21 at 11:14

0 Answers0