What is the correct way of freeing the memory of an std::vector
of struct
?
Consider the following pseudo-code:
typedef struct
{
unsigned int packageLen;
unsigned char* package;
} PACKAGE;
std::vector<PACKAGE*>* packages = new std::vector<PACKAGE*>;
for (...)
{
PACKAGE *tempPackage = new PACKAGE;
// Set data of package
packages->pushback(tempPackage);
}
// Function exit
if (packages)
delete packages;
Would this correctly free the assigned memory?
No, you are leaking memory. Here's a the right wayTM
struct Package
{
// ...
};
int main()
{
std::vector<Package> packages; // no pointers involved
// Can use vector::reserve at this point if you know how many
// elements you are going to need
for (...)
{
packages.push_back({ /*...*/ }); // may also add a constructor and call emplace_back
// Use packages.back() or other elements as you need
}
// No need to free anything
}
You can, of course, improve this code to cater your specific case. For instance, if you know exactly how many elements you want to default initialize, you can just create them all in the constructor.