Hello so I have bumped into a small dilemma today.
I have one example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
void SomeFunction(int* pInt){
int myInt = 25;
pInt = &myInt;
cout << *pInt << endl;
}
int main(){
int* pInt;
SomeFunction(pInt);
cout << *pInt << endl;
}
|
If I do that, I get, as I expect, a segmentation fault (core dumped) on the second print.
Correct me if I am wrong, this is because I have declared a local var in another function, given it a value, pointed a pointer at it, then exited the function. As a result, the var is deleted, and the pointer is pointing to nothing real, so I get a segmentation fault.
My next example (the one I really dont get).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
int* SomeFunction(){
int myInt = 25;
int* pInt = &myInt;
cout << "pInt: " << *pInt << endl;
return &myInt;
}
int main(){
int* pReceivedInt = SomeFunction();
cout << *pReceivedInt<< endl;
}
|
I get
test2.cxx:8: warning: address of local variable ‘myInt’ returned
But when I run, I get desired output.
pInt: 25
25
My question is - why do I get that second 25 on the output? Should't I get a segmentation fault as in the first program? What is going on here? Is the function not being deleted because I am returning a pointer? I have a situation where I am returning a 4 byte? pointer, which is fine, its data as well, but its pointing to some other local thing that SHOULD be deleted once I exit function.
Please explain!