Can't understand the output of this program

Hi I executed the following program -:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
#include<string>

using namespace std;

int main(){

int *p = (int *)1;

bool b = p;

cout << p << " " << *p << endl;

return 0;
}

and got the following output 0x1 and Segmentation fault but I don't really know whats happening under the hood, can anybody explain me what is happening internally.

Thanks in advance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include<string>
using namespace std;

int main()
{
    int *p = (int *)1; //You are forcibly assigning pointer value of 1.
                       //So it is pointing to memory at address 1, 
                       //which usually is not avaliable to program
    bool b = p; //Implicit conversion pointer>bool. Everything aside null pointer is true
    cout << p << //Here you outputting address p is pointing to. You assigned it one two lines earlier
            " " << *p << endl; //Here you are trying to dereference said pointer which lead to
                               //access to unavaliable memory and crash
}
Last edited on
Topic archived. No new replies allowed.