but it segfaults on a 64bit computer
The likely reason is that, on your platform, pointers are 64-bit and ints are 32-bit. Thus when you cast the pointer to int
, you lose information.
My compiler specifically warns about this:
test.c:7:19: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
This is easy to see using the following program:
#include <stdio.h>
int main()
{
char *s = "";
printf("%p %p\n", s, (char*)(int)s);
return 0;
}
On my computer, this prints two different addresses (the second has its top bits chopped off).
what I don't quite understand is that both b1 and b2 are char*, and they both point to the same address
Actually, they don't point to the same address. Your printf()
format specifiers are all wrong. The first printf()
should be:
printf("B1 Points to %p - B2 Points to %p\n", b1, b2);
When you run this, you'll see that the addresses differ.