Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why local variable is sustain when using pointer in C++?

#include <iostream>

int* dont() {
    int num = 10;
    int* num_ptr = &num;
    return num_ptr;
}

int main() {
    int* a = nullptr;
    a = dont();
    std::cout << *a;
}

This is my code sample. I think ‘a’ would have garbage value, but memory is still alive. I cannot understand what it is, please help me ! (I use visual studio 2022 for my IDE)

  • precisely what i want to know is pointer ‘a’ must be dangling pointer. But it wasnt. I cannot understand this situation..

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Returning a pointer to a local variable and then dereferencing that pointer invoke undefined behavior. Anything can happen, but that doesn’t mean you necessarily get a garbage value. The program can "work" as an option.

The likelihood of this option is increased in this case as no other functions are called in the interim, reducing the odds that the memory location you’re accessing has been overwritten.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading