undefined behavior - C - function returning a pointer to a local variable -


consider following code.

#include<stdio.h> int *abc(); // function returns pointer of type int  int main() {     int *ptr;     ptr = abc();     printf("%d", *ptr);     return 0; }  int *abc() {     int = 45500, *p;     p = &i;     return p; } 

output:

45500

i know according link type of behavior undefined. why getting correct value everytime run program.

every time call abc "marks" region @ top of stack place write of local variables. moving pointer indicates top of stack is. region called stack frame. when function returns, indicates not want use region anymore moving stack pointer originally. result, if call other functions afterwards, reuse region of stack own purposes. in case, haven't called other functions yet. region of stack left in same state.

all above explain behavior of code. not necessary c compilers implement functions way , therefore you should not rely on behavior.


Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -