I have a program in which I collect some data and store them temporarily in a deque
typedef vector<float> floatVector;
...
floatVector * currRecord;
deque<floatVector *> data;
...
...
for (...)
{
...
currRecord = new floatVector(10);
data.push_back(currRecord);
}
Later, I want to save data to file
while (data.size() > 0)
{
for (int i=0; i < 10; i++)
{
fprintf(fPtr, "%lf\t", data[0]->at(i) );
}
fprintf(fPtr,"\n");
data.pop_front();
}
So, my question is, will this program cause a memory leak? I use new operator to allocate memory for each currRecord vector. Will the deque pop_front function automatically recycle memory? Or do I need to put
delete [] data[0]
before
data.pop_front();
? Also, if data is a vector instead of a deque, will everything be the same? Thanks!
You have a
std::dequeof pointers and each pointer owns a resource (memory). Callingpop_front()will remove a pointer from the container but it doesn’t release the memory the pointer owns. Since you allocate the memory withnewyou must also calldelete. The situation is unchanged if the container is astd::vector.You could avoid memory leaks if you changed to a
std::deque<floatvector>or a container of smart pointers likestd::shared_ptr.Note that you didn’t use
[]when you callednewso use plaindeletewithout square brackets.