Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int * add(int x, int y) {
- int z = x + y;
- int *ans_ptr = &z;
- return ans_ptr;
- }
- int main() {
- int ans = *(add(1, 2));
- int *ans_ptr = add(1, 2);
- printf("%dn", *ans_ptr);
- printf("%dn", ans);
- return 0;
- }
- int * add(int x, int y) {
- int z = x + y; //z is a local variable in this stack frame
- int *ans_ptr = &z; // ans_ptr points to z
- return ans_ptr;
- }
- // at return of function, z is destroyed, so what does ans_ptr point to? No one knows. UB results
- ccc-analyzer -c foo.c
- ...
- ANALYZE: foo.c add
- foo.c:6:5: warning: Address of stack memory associated with local
- variable 'z' returned to caller
- return ans_ptr;
- ^ ~~~~~~~
Advertisement
Add Comment
Please, Sign In to add comment