After dynamically allocating struct, I thought it woudl be prudent to put 'delete' at the end. But it gave me a runtime error. Compiled ok, though. So if I get rid of 'delete', it runs fine. But I worry there could be a memory leak. What would be the safe way to handle this code?
#include <iostream>
#include <vector>
using namespace std;
typedef struct
{
vector<char*> vstr;
vector<int> vint;
}VecStrInt;
int main()
{
VecStrInt * mtx = new VecStrInt();
mtx[0].vstr.push_back("Hello");
mtx[0].vint.push_back(1);
cout<<mtx[0].vint.at(0)<<endl;
cout<<mtx[0].vstr.at(0)<<endl;
//delete [] mtx;
return 0;
}
The call of delete[] is not the same as the call of delete (note the square brackets).
You pair calls of delete with calls of new, and calls of delete[] with calls of new SomeType[someCount].
In your case, you allocated a single object, not an array. Your object happens to represent a vector, which is an array, but it does not matter to C++: you allocated it with a "single" new, so you cannot apply an "array" delete[] to it.
Hence, you need to delete it using the regular delete operator:
delete mtx;
Note: there is rarely a situation when you should allocate std::vector<T> dynamically. The object that represents std::vector<T> itself is very small; the data is stored elsewhere, and is allocated dynamically. So you might as well use
VecStrInt mtx;
and skip delete altogether.
If you allocate only a single object like this then you have to use operator delete
VecStrInt * mtx = new VecStrInt();
//...
delete mtx;
If you allocate an array of objects (even if the array contains only one element) you have to use operator delete[] like this
VecStrInt * mtx = new VecStrInt[1];
//...
delete [] mtx;
Also you could use a standard smart pointer as for example std::unique_ptr.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With