Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 633
trueCodian Avatar asked Dec 11 '25 13:12

trueCodian


2 Answers

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.

like image 87
Sergey Kalinichenko Avatar answered Dec 14 '25 02:12

Sergey Kalinichenko


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.

like image 44
Vlad from Moscow Avatar answered Dec 14 '25 04:12

Vlad from Moscow