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

6
  • Because it's undefined behavior. Also open your C++ book to the chapter that explains how parameters are passed by value. Commented Dec 13, 2018 at 13:34
  • related: stackoverflow.com/questions/6441218/… and stackoverflow.com/questions/373419/… Commented Dec 13, 2018 at 13:34
  • 2
    You probably want to take input by reference and not by value: int input =>int& input Commented Dec 13, 2018 at 13:36
  • @AMA: Then the OP would be advised to change the return type to const int*. Commented Dec 13, 2018 at 13:40
  • 2
    @AMA: If I continue to type, will you fix the bugs in my code too ;-) ? Commented Dec 13, 2018 at 13:41

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It's implementation defined since C++14
@PasserBy: So it is: which accounts for the nullptr value.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.