fork download
  1. #include <iostream>
  2.  
  3. int* getInt1(int input)
  4. {
  5. int i = input;
  6. std::cout << "created 'i' at " << (void*)&i << std::endl;
  7. int* ptr1 = &i;
  8. return ptr1;
  9. }
  10.  
  11. int* getInt2(int input)
  12. {
  13. int* ptr3 = new int(input);
  14. return ptr3;
  15. }
  16.  
  17. int main()
  18. {
  19. int i = 0;
  20. std::cout << "i is on the stack, it's address is " << (void*)&i << std::endl;
  21. int* ip = new int(1);
  22. std::cout << "ip is on the heap, it's address is " << (void*)ip << std::endl;
  23.  
  24. int* p1 = NULL;
  25. int* p2 = NULL;
  26. int* p3 = NULL;
  27. // force the pointers to be assigned locations on the stack by printing them.
  28. std::cout << "created p1(" << &p1 << "), p2(" << &p2 << ") and p3(" << &p3 << ")" << std::endl;
  29.  
  30. p1 = getInt1(10101);
  31. std::cout << "p1(" << &p1 << ") = " << (void*)p1 << " -> " << *p1 << std::endl;
  32.  
  33. p2 = getInt1(20202);
  34. std::cout << "p2(" << &p2 << ") = " << (void*)p2 << " -> " << *p2 << std::endl;
  35.  
  36. // but more importantly
  37. std::cout << "p1(" << &p1 << ") = " << (void*)p1 << " -> " << *p1 << std::endl;
  38.  
  39. p3 = getInt2(30303);
  40. std::cout << "p3(" << &p3 << ") = " << (void*)p3 << " -> " << *p3 << std::endl;
  41. std::cout << "p2(" << &p2 << ") = " << (void*)p2 << " -> " << *p2 << std::endl;
  42. std::cout << "p1(" << &p1 << ") = " << (void*)p1 << " -> " << *p1 << std::endl;
  43. }
  44.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
i is on the stack, it's address is 0xbfb49a90
ip is on the heap, it's address is 0x9b83008
created p1(0xbfb49a94), p2(0xbfb49a98) and p3(0xbfb49a9c)
created 'i' at 0xbfb49a6c
p1(0xbfb49a94) = 0xbfb49a6c -> 10101
created 'i' at 0xbfb49a6c
p2(0xbfb49a98) = 0xbfb49a6c -> 20202
p1(0xbfb49a94) = 0xbfb49a6c -> -1078682988
p3(0xbfb49a9c) = 0x9b83018 -> 30303
p2(0xbfb49a98) = 0xbfb49a6c -> -1078682988
p1(0xbfb49a94) = 0xbfb49a6c -> -1078682988