When I run the following code I get a segmentation fault.
Code:
#include <iostream>
using namespace std;
typedef int* IntPointer;
void notsneaky(IntPointer temp);
void sneaky(IntPointer temp);
void sneakybutnotsneaky(IntPointer& temp);
int main()
{
IntPointer p;
p = new int;
*p = 77;
cout<<"Before call to function *p == "
<< *p << endl;
notsneaky(p);
cout<<"After call to \"notsneaky\" function *p == "
<< *p << endl;
sneaky(p);
cout<<"After call to \"sneaky\" function *p == "
<< *p << endl;
sneakybutnotsneaky(p);
cout<<"After call to \"sneaky_but_notsneaky\" function *p == "
<< *p << endl;
return 0;
}
void notsneaky(IntPointer temp)
{
int *ptr;
*ptr=23;
temp = ptr;
cout<<"Inside the function call *temp == "
<<*temp<<endl;
}
void sneaky(IntPointer temp)
{
*temp = 99;
cout<<"Inside the function call *temp == "
<<*temp<<endl;
}
void sneakybutnotsneaky(IntPointer& temp)
{
int *ptr;
*ptr=37;
temp = ptr;
cout<<"Inside the function call *temp == "
<<*temp<<endl;
}
Here is the output:
Code:
thetinman@computer:~/code$ ./a.out
Before call to function *p == 77
Inside the function call *temp == 23
After call to "notsneaky" function *p == 77
Inside the function call *temp == 99
After call to "sneaky" function *p == 99
Segmentation fault
Does anyonone know what is causing this segmentation fault? How should I go about fixing it?