returning address of stack variable in function
In function fun, address of stack variable(a) is copied to ptr.
But as soon as program control comes out of function, stack variables gets cleaned. So inside main(), program should not have printed value of a. But here, I am able to print the content inside main(). Is this expected ? Code:
#include<stdio.h> Code:
./a.out |
humm
Code:
#include<stdio.h> Code:
$ ./a.out |
@OP: What you see is accidental working, but what you should achieve is reliable working.
The memory on the stack might not have been overwritten that moment, but sooner or later it will be overwritten, and your data will be lost. Also stack is allowed to grow and shrink on demand, so a pointer that points to a currently unused stack-area might become invalid pointer that causes segmentation fault when you try to use the pointed value. |
Quote:
Your code is the reverse of how I'd pass a pointer and use it, crude example. I'd likely check for a NULL pointer and return a status from fun(), neither of which is done here: Code:
#include <stdio.h> |
This is playing the lottery.
Might work right now, might stop working if you use a different (version of the ) compiler, different optimizations, etc. It's like using uninitialized variables. Some hypothetical int in a different code might be initialized 'by itself' to 0x00000000 to you, might do it to 0xdeadbeef for someone else, or yourself at another compilation. |
more pointer math?
Code:
#include<stdio.h> Code:
$ ./a.out |
Conclusion:
============== 1. such results are compiler specific. 2. so even after stack unwinding, variables take some time to cleanup. |
Quote:
Memory assigned with malloc is allocated on the heap and until freed will remain available to your program so a pointer can be assigned to and returned from a function and safely used. A pointer to a local variable can be passed to a function and assigned then read after the function returns because it is on the calling functions stack, not the receiving function. |
Huh. This prints out a warning:
Code:
#include <stdio.h> Code:
stack2.c: In function ‘fun’: Code:
#include <stdio.h> And clang-check didn't catch it either. |
Quote:
What would be helpful here is what you're trying to figure out or learn. Results are system specific and the stack is not cleaned up. Why did you write that program initially, and what were you intending to explore/learn? |
Let this be a lesson about the benefits of modern C/C++ tooling.
Code:
❯ cat stack3.c |
i always find it more beneficial to concentrate on studying good code, not bad.
|
All times are GMT -5. The time now is 05:05 PM. |