0

I encountered a very strange thing today. I found that the following code will trigger a breakpoint, maybe because the memory of the class object "b" I created in qqq() is released, and the pointer will be invalid.

#include<iostream>
#include<vector>
#include"ww.h"//A header file for a class I defined, which has a class called apple in it
using namespace std;

vector<apple*>arr_apple_p;
void qqq(apple* &);

int main()
{
    apple* p_apple=NULL;
    qqq(p_apple);
    arr_apple_p[0]->print();
}

void qqq(apple* &a)
{
    apple b;
    a = &b;
    arr_apple_p.push_back(a);
}

However, if I change the code

arr_apple_p[0]->print();

to

p_apple->print();

It will work fine! I'm wondering why this is?

  • The behavior of *undefined behavior* is undefined. It may appear to work correctly, but that doesn't mean that it is – UnholySheep Jun 03 '22 at 12:53
  • 1
    "maybe because the memory of the class object "b" I created in qqq() is released" - not maybe, for sure. – pptaszni Jun 03 '22 at 12:55
  • You can't take the address of a local object and use it after you have returned from that function. In this case `b` only lives from the time `qqq` is called and to when control returns from it. – Lindydancer Jun 03 '22 at 12:58
  • @UnholySheep So that means the pointer "p_apple" is also invalid? – spciyofwolf123 Jun 03 '22 at 12:58
  • `p_apple->print();` does not work fine. The object you are trying to `print` has its lifetime already ended. Calling `print` on it is undefined behavior. Anything can happen. – 463035818_is_not_an_ai Jun 03 '22 at 13:00
  • fwiw, your line of reasoning is flawed. Getting expected results do not imply that the code is correct. My favourite example is multiplying numbers: x+y is wrong even though 2+2 yields the expected result. – 463035818_is_not_an_ai Jun 03 '22 at 13:06
  • @spciyofwolf123 -- The other thing you should realize when you're doing these "undefined behavior" tests is that if the compiler detects the code is nonsense, the compiler is within its rights to remove the code from the final executable, or practically do anything with that code. For example: `if (this == nullptr)` is a nonsense comparison, since that can never happen -- thus the compiler is free to remove tests like this, or replace it with `if (true)` or whatever else it may want to do with it. – PaulMcKenzie Jun 03 '22 at 13:48
  • *I'm wondering why this is?* C++ isn't a nanny language. It gives you enough rope to shoot yourself in the foot. – Eljay Jun 03 '22 at 13:58

0 Answers0