Guest User

Untitled

a guest
Jun 20th, 2013
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int * add(int x, int y) {
  4. int z = x + y;
  5. int *ans_ptr = &z;
  6. return ans_ptr;
  7. }
  8.  
  9. int main() {
  10. int ans = *(add(1, 2));
  11. int *ans_ptr = add(1, 2);
  12.  
  13. printf("%dn", *ans_ptr);
  14. printf("%dn", ans);
  15.  
  16. return 0;
  17. }
  18.  
  19. int * add(int x, int y) {
  20. int z = x + y; //z is a local variable in this stack frame
  21. int *ans_ptr = &z; // ans_ptr points to z
  22. return ans_ptr;
  23. }
  24.  
  25.  
  26. // at return of function, z is destroyed, so what does ans_ptr point to? No one knows. UB results
  27.  
  28. ccc-analyzer -c foo.c
  29. ...
  30. ANALYZE: foo.c add
  31. foo.c:6:5: warning: Address of stack memory associated with local
  32. variable 'z' returned to caller
  33. return ans_ptr;
  34. ^ ~~~~~~~
Advertisement
Add Comment
Please, Sign In to add comment