Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector memory allocation issue

I have a problem when trying to delete a vector of pointers:

std::vector<float*> *v;

v = new std::vector<float*>;
v->assign(2, new float[2]);

for (int i = 0; i < 2; ++i)
{
    delete[] v->at(i);
}
delete v;

I'm deleting each element from the whole vector, but I still get an assert. Can you please tell me what I'm doing wrong?

Thank you in advance.

like image 740
user1917028 Avatar asked Jan 27 '26 13:01

user1917028


2 Answers

This doesn't do what you think it does:

v->assign(2, new float[2]);

One array of size 2 is allocated, then two pointers to it are stored in the vector. When you delete, the same pointer is deleted twice.

If you want a multidimensional array, you could try std::vector< std::array< float, 2 > >. Doing new and delete yourself are a code smell. (The same goes for new vector …; that is probably not what you really want.)

like image 121
Potatoswatter Avatar answered Jan 29 '26 01:01

Potatoswatter


THe v->assign(2, new float[2]) does the same as :

float *f = new float[2];
for(int i = 0; i < 2; i++)
   v->push_back(f);

of course, that's MOST likely not what you want - you probably want:

for(int i = 0; i < 2; i++)
{
   float *f = new float[2];
   v->push_back(f);
}

And using new on vector is just plain wrong - just use a plain vector. Inside it, put a vector<float> - or, if you just want two elements every time, use something like:

struct f2 { float a; float b; };
vector<struct f2> v;
like image 23
Mats Petersson Avatar answered Jan 29 '26 03:01

Mats Petersson