C - function returning a pointer to a local variable

后端 未结 2 1186
渐次进展
渐次进展 2020-11-30 15:27

Consider the following code.

#include
int *abc(); // this function returns a pointer of type int

int main()
{
    int *ptr;
    ptr = abc();
         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 15:38

    Well, undefined behavior is, undefined. You can never rely on UB (or on an output of a program invoking UB).

    Maybe, just maybe in your environment and for your code, the memory location allocated for the local variable is not reclaimed by the OS and still accessible, but there's no guarantee that it will have the same behavior for any other platform.

提交回复
热议问题