Reputation: 97
Can anyone tell me why this piece of code does not work? It always says segmentation fault
int main()
{
int a = 10;
int b = (int)&a;
int *c = (int*)b;
printf("%d", *c);
return 0;
}
When I print the value of c
, it is the address of a
as I expect, but when I deference it, a segmentation fault happens. Assume that this is a 32bit compiler.
Upvotes: 3
Views: 183
Reputation: 39
Sometimes it will work and sometimes do not , it depends on your machine , maybe the size of integer is less than the size of the pointer in your machine , so if the address that's casted and assigned to integer is larger than the size of int ,it will overflow and the integer will hold an incorrect address so the output will give segmentation fault.
Note
you can check the size of the type using sizeof function.
size_t a,b;
a=sizeof(int);
b=sizeof(int*);
if(a>=b)
printf("Valid assignment with no errors\n);
else
printf("This may cause an error if the address is larger than integer size\n);
Upvotes: 3
Reputation: 1732
a
is an int and gets the value 10.
b
is an int and gets as a value an int, the address of a
casted as an int.
c
is a pointer to an int and gets the value b
casted to be a pointer to an int.
The value of b
was the address of a
, but casted as an int.
So c
"should" point to a
and with *c
you "should" get 10. The problem is that on your machine the size of an int
and the size of a pointer to an int
are not the same and in the first cast you truncated the value of &a
to fit into the size of an int and lost some digits of the address.
Now in b
there is an int containing only some digit of the address of a
and therefore a completely different address , so when you try to access the memory at that address (with *c
) you're not accessing a
, but some memory somewhere else that in this case happens to be invalid.
Upvotes: 6