3

I'm playing around with pointers to understand this concept better and wanted to ask

Why do i get null pointer as return for the second function?

and why it isn't possible to get the address 0x7fff15504044. What is happening and where inside memory is the integer 5 stored, when im working with it inside the function?.

#include <iostream>
using namespace std;

int* return_adress(int* input){ return input; }

int* return_adress_from_input(int input){ return &input; }

int main(){
    int k = 3; 
    cout << return_adress(&k) << endl;
    cout << return_adress_from_input(k) << endl;
}

Output:

0x7fff15504044

0

Alperen Kantarcı
  • 1,038
  • 9
  • 27
Landau
  • 121
  • 7
  • Because it's undefined behavior. Also open your C++ book to the chapter that explains how parameters are passed by value. – Sam Varshavchik Dec 13 '18 at 13:34
  • related: https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope and https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value – NathanOliver Dec 13 '18 at 13:34
  • 2
    You probably want to take `input` by reference and not by value: `int input` =>`int& input` – AMA Dec 13 '18 at 13:36
  • @AMA: Then the OP would be advised to change the return type to `const int*`. – Bathsheba Dec 13 '18 at 13:40
  • @Bathsheba fixed while you were typing :) – AMA Dec 13 '18 at 13:41
  • 2
    @AMA: If I continue to type, will you fix the bugs in my code too ;-) ? – Bathsheba Dec 13 '18 at 13:41

2 Answers2

7

With int* return_adress_from_input(int input), input is a value copy of k in the caller. They are two different variables therefore with different addresses.

input goes out of scope conceptually once the closing brace of the function is reached.

The pointer &input then points to memory that you no longer own, and the behaviour of reading that pointer value (let alone dereferencing it) is undefined prior to C++14, and implementation defined from and including C++14.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Because you pass input by value, not by reference. Compiller first creates a local copy of input and then returns address of this local copy. To get the variable address use

int* return_adress_from_input(int& input){ return &input; }

In general, you get undefined behavior which can lead to returning nullptr in the particular case

On my PC i get

00AFFC80
00AFFBA8

so you are just lucky with zero return

Dmytro Dadyka
  • 2,208
  • 5
  • 18
  • 31