Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior after deleting a pointer in a vector

I was experimenting with vectors of pointers and came across the following behavior which I don't quite understand:

#include <iostream>
#include <vector>

int main()
{
    std::vector<int*> vec;

    int* p1 = new int;
    *p1 = 100;

    vec.push_back(p1);  
    std::cout << *vec[0] << std::endl;

    delete p1;
    std::cout << *vec[0] << std::endl;

    int* p2 = new int;
    *p2 = 200;

    std::cout << *vec[0] << std::endl;

    return 0;
}

Using the MinGW C++ compiler (g++), this gave me the following output:

100
5640648
200

Now of course the actual element vec[0] was not erased when deleting the pointer, but note that p2 is not inserted in the vector at all. Still, printing the value of the first element returns the value of this seemingly unrelated pointer! Also, restructuring the code a little bit so that p2 is declared before deleting p1 does not yield this behavior.

Just to make sure, I also compiled this with MSVC++, which gave me the following (expected) output:

100
5484120
5484120

Does anyone have an explanation for the first output?

like image 261
mhjlam Avatar asked Dec 21 '22 02:12

mhjlam


2 Answers

because after delete you access the memory it causes undefined behavior:

delete p1;
std::cout << *vec[0] << std::endl;  <-- Buggy code

undefined behavior: - No guaranty how it will work

like image 146
Grijesh Chauhan Avatar answered Jan 22 '23 14:01

Grijesh Chauhan


It reallocated the space held by p1, which vec[0] was still pointing to, hence the 200 value that showed up.

As you have noticed, this was the behavior of one compiler, and another compiler acted differently. You may have other behaviors based on different optimization switches as well. So overall, the behavior is undefined, though we can sometimes figure out what happened in particular cases.

like image 33
Jiminion Avatar answered Jan 22 '23 14:01

Jiminion