0

Why C++ returns valid data from curly brackets scope inside function if i point data from this scope to a pointer that was declared outside these curly brackets scope?

Example:

int *pInt;
// why *pInt is still "valid" ?
{
    int x = 134;
    pInt = &x;
}
cout << *pInt << endl;
// *pInt returns 134

Another example:

// or why *pChar is still "valid" ?
char *pChar;
{
    char cArr[] = { 'Y', 'o', '!', '\0' };
    pChar = cArr;
}
cout << pChar << endl;
// pChar returns 'Yo!'

I do not understand this, because in this case:

int * invalid_pointer(){
    int x = 134;
    return &x;
}

int main(void){
    int *pInt = invalid_pointer();
    cout << *pInt << endl;
    return 0;
}

*pInt wil be '2079168904', which is invalid value, and that is correct behavior in such case, and i expected the same behavior with curly brackets case.

Please explain why these two cases are different. Thanks!

hgrev
  • 107
  • 7
  • 5
    *"and that is correct behavior in such case"* - The behavior is undefined. There is no "correct" here. – StoryTeller - Unslander Monica Oct 06 '21 at 13:40
  • 1
    UB is UB (for all your snippets), and seems to works is a valid behavior. – Jarod42 Oct 06 '21 at 13:40
  • 2
    And that's the thing... this job would have been **easier** if UB meant the program always blows up immediately. – StoryTeller - Unslander Monica Oct 06 '21 at 13:43
  • In your first example, `pInt` is not valid anymore. It may happen to give the "right" result (as you see), but you are skating on thin ice. A little more about the "why": Even though `x` has been deallocated, the memory space in this case has not been put to another use so the value is preserved. However, this is by "luck", it is not guaranteed. In the second example, the memory has been put to other use and you see the new value that is stored in this location. – nielsen Oct 06 '21 at 13:44
  • 1
    thanks everyone for answering the questions, i was a bit confused of this "undefined" style of behaviour, at least now it seems more clear what to expect! – hgrev Oct 06 '21 at 13:46

0 Answers0