I was playing around with c pointer and wrote this code
#include <stdio.h>
int main() {
int a = 17;
int* p1 = &a;
int* p2 = (int*)(&p1);
p1 = (int*)(&p2);
printf("%d\n", *((int*)(*p1)));
printf("%d\n", *((int*)(*p2)));
return 0;
}
the program exit with
[Done] exited with code=3221225477 in 0.23 seconds
the pointers work as expected
#include <stdio.h>
int main() {
int a = 17;
int* p1 = &a;
int* p2 = (int*)(&p1);
p1 = (int*)(&p2);
printf("&p1 %d\n", &p1);
printf("&p2 %d\n", &p2);
printf("p1 %d\n", p1);
printf("p2 %d\n", p2);
printf("*p1 %d\n", *p1);
printf("*p2 %d\n", *p2);
// printf("%d\n", *((int*)(*p1)));
// printf("%d\n", *((int*)(*p2)));
return 0;
}
&p1 748680992
&p2 748680984
p1 748680984
p2 748680992
*p1 748680992
*p2 748680984
it only stopped working when i try to dereference arbitrary-ish address
according to the answers from another question, the reason dereferencing arbitrary memory address doesn't work is because the address is invalid
but here i dereference an address that i was able to dereference just fine before
is this because of some kind of protection to prevent bad code? if so i want to know the specifics of the protection mechanism or i'm just doing it wrong for what i'm trying to achieve?
Lets work through all your printf's,
There is never an arbitrary address being dereferenced, so no segfaults.
printf is probably just casting pointers to ints.
Try
printf( "%ld\n", (uintptr_t)&p1 );ldfor long int,uintptr_tis casting a pointer to unsigned int.