What's the safe way to dynamically allocate vector in C++

c++, dynamic-allocation, vector

Solution

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.

Problem

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; } ```

Original source