Shouldn't std::unique_ptr
prevent the possibility of such an error?
#include <iostream>
#include <vector>
#include <memory>
struct B {
int b;
};
int main()
{
std::vector<std::unique_ptr<B>> v; // unique_ptr can be stored in a container
B* p = new B;
v.emplace_back(p);
std::cout << "p:" <<p <<"\n";
std::cout << "v[0]:"<<v[0].get() << "\n";
v.emplace_back(p);
std::cout << "p:" <<p <<"\n";
std::cout << "v[1]:"<<v[1].get() << "\n";
}
Error message when double free is detected:
*** Error in `./a.out': double free or corruption (fasttop): 0x0000000001094c20 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f3da200b7e5]
...
======= Memory map: ========
00400000-00402000 r-xp 00000000 ca:01 3228321 /tmp/1617748074.6996937/a.out
...
Output when double free is ignored:
p:0x1094c20
v[0]:0x1094c20
p:0x1094c20
v[1]:0x1094c20