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?