Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returns null pointer instead of address

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

like image 545
Landau Avatar asked Feb 01 '26 23:02

Landau


1 Answers

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.

like image 143
Bathsheba Avatar answered Feb 03 '26 14:02

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!