C is a function that returns a pointer to a local variable

Consider the following code.

#include<stdio.h>
int *abc(); // this function returns a pointer of type int

int main()
{
    int *ptr;
    ptr = abc();
    printf("%d", *ptr);
    return 0;
}

int *abc()
{
    int i = 45500, *p;
    p = &i;
    return p;
}

Conclusion:

45500

I know, according to the link , this type of behavior is undefined. But why do I get the correct value every time I run the program.

+4
source share
2 answers

, abc, "" , . , , , . . , , , , . , , . . , .

. , C , .

+3

, undefined , undefined. UB ( , UB).

, , , , , , , , .

+2

Source: https://habr.com/ru/post/1653924/


All Articles