mercredi 1 août 2018

Unique_ptr: pointer being freed was not allocated when emplaced in list

I have a simple C++ program like so:

#include <iostream>
#include <list>
#include <memory>

int main(void) {
  std::list<std::unique_ptr<int>> l;
  int x = 5;
  // throws runtime error: pointer being freed was not allocated
  l.emplace_back(&x);
}

When the program is run I obtain the following output:

a.out(59842,0x7fffb13d1380) malloc: *** error for object 0x7ffee81489ac: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug [1] 59842 abort ./a.out

This tells me that during the destruction of the list the unique_ptr object that had been created is being destroyed, and during that destruction the pointer to x is being freed when it was never malloced.

However I would expect that the same would occur in this situation where a unique_ptr falls out of scope and is destroyed:

#include <iostream>
#include <list>
#include <memory>

int main(void) {
  int x = 5;

  // does not throw runtime error when falling out of scope and being destructed
  std::unique_ptr<int> p(&x);
}

However when the unique_ptr p above falls out of scope and is destroyed the program runs fine. Why is the first program giving me an error when destroying the unique_ptr but the second one is not? Why does emplacing the unique_ptr in a list cause its destruction to fail?

Aucun commentaire:

Enregistrer un commentaire