Reputation: 69
If I initialize a vector with a dynamically allocated array, then later the vector goes out of scope and is to be freed, does the vector free the memory from the array that it is wrapping? More specifically, say I have an example function:
std::vector<float> mem_test() {
unsigned char* out = new unsigned char[10];
for (int i = 0; i < 10; i++) {
out[i] = i * i;
}
std::vector<float> test_out(out, out + 10);
return test_out;
}
int main() {
std::vector<float> whatever = mem_test();
// Do stuff with vector
// Free vector
std::vector<float>().swap(whatever);
}
When the vector returned from the function goes out of scope or is manually freed, will the underlying dynamically allocated array also have its memory freed?
Upvotes: 2
Views: 168
Reputation: 595349
does the vector free the memory from the array that it is wrapping?
The vector does not wrap the array at all.
When the vector returned from the function goes out of scope or is manually freed, will the underlying dynamically allocated array also have its memory freed?
No. You are constructing the vector using a constructor that takes 2 iterators as input. It iterates through the source array copying the values of its elements into the vector's internal array. The source array itself is keep separate and must be delete[]
'd explicitly before mem_test()
exits or else it will be leaked.
std::vector<float> mem_test() {
unsigned char* out = new unsigned char[10];
for (int i = 0; i < 10; i++) {
out[i] = i * i;
}
std::vector<float> test_out(out, out + 10);
delete[] out; // <-- HERE
return test_out;
}
Alternatively:
std::vector<float> mem_test() {
std::unique_ptr<unsigned char[]> out(new unsigned char[10]); // <-- auto delete[]'d
for (int i = 0; i < 10; i++) {
out[i] = i * i;
}
std::vector<float> test_out(out.get(), out.get() + 10);
return test_out;
}
Upvotes: 3