Hi All
I am trying the below code in Linux platform using GNU compiler - g++ . It got compiled and generated executable. However I got "Segmentation fault" error during execution .
Can you please help me why the char pointer failed to read 1 byte of memory .
The error is caused by the line
"printf("%c",*p);"
#include<stdio.h>
int main()
{
int x= 23458;
char *p=(char*)x;
printf("%c",*p);
}
Your code makes an int, 23458, and then creates a char pointer, pointing at memory location 23458 (note that it is NOT pointing at the memory location containing the int you made; the code for that would be char *p=(char*)&x; ).
You then try to read memory location 23458. The operating system, amongst its many jobs, is keeping an eye on your program and will stop it with a segmentation fault if you try to read or write memory that the operating system thinks you shouldn't be. Clearly, memory location 23458 is a memory location that the operating system doesn't think you should be looking at, so it calls a halt to the whole thing with a segmentation fault.