Back to questions
JuniorTheoryCommon
What happens when this program runs?
#include <iostream>
int main() {
int* p = new int{42};
int* q = p;
delete q;
std::cout << *p << '\n';
}Undefined behavior: p and q hold one address, and its int was deleted
- Expecting
pto keep its own int:q = pcopies the address, not the int, sodelete qdestroys the only int and*preads a deleted object. - Expecting a guaranteed crash: reading after
deleteis undefined behavior, and the standard promises no crash or any other outcome.
- Why does assigning
q = nullptrafterdelete qnot make*psafe? - How would a
std::unique_ptrowning the int prevent this bug?