Introduction: This question is part of my collection of C and C++ (and C/C++ common subset) questions regarding the cases where pointers object with strictly identical byte-wise representation are allowed to have different "values", that is, to behave differently for some operation (including to have defined behavior on one object and undefined behavior on the other).
Following another question which caused much confusion, here is question about pointer semantics that will hopefully clear things up:
Is this program valid in all cases? The only interesting part is in the "pa1 == pb" branch.
#include <stdio.h>
#include <string.h>
int main() {
int a[1] = { 0 }, *pa1 = &a[0] + 1, b = 1, *pb = &b;
if (memcmp (&pa1, &pb, sizeof pa1) == 0) {
int *p;
printf ("pa1 == pb\n"); // interesting part
memcpy (&p, &pa1, sizeof p); // make a copy of the representation
memcpy (&pa1, &p, sizeof p); // pa1 is a copy of the bytes of pa1 now
// and the bytes of pa1 happens to be the bytes of pb
*pa1 = 2; // does pa1 legally point to b?
}
else {
printf ("pa1 != pb\n"); // failed experiment, nothing to see
pa1 = &a[0]; // ensure well defined behavior in printf
}
printf ("b = %d *pa1 = %d\n", b, *pa1);
return 0;
}
I would like an answer based on standard quotes.
EDIT
By popular demand, here is what I want to know:
- is a pointer's semantic "value" (its behavior according to the specification) determined only by its numerical value (the numerical address it contains), for a pointer of a given type?
- if not, it is possible to copy only the physical address contained in a pointer while leaving out the associated semantic?
Here let's say that some one past the end pointer happens to accidentally point to another object; how can I use such one past the end pointer to access the other object?
I have the right to do anything, except use a copy of the address of the other object. (It's a game to understand pointers in C.)
IOW, I try to recycle dirty money just like the mafia. But I recycle a dirty pointer by extracting its value representation. Then it looks like the clean money, I mean pointer. Nobody can tell the difference, no?
memcpy( &p, &pa1, sizeof p )
andmemcpy( &pa1, &p, sizeof p )
supposed to do, in your own words? Also, you really should add some lines about your intent with thememcmp
(see my comment to Sourav Ghosh). – Auldint
; not transfer semantic – Pang*pa1 = &a[0] + 1
), then 2) prove that it's the same bit pattern as another, legal pointer (*pb = &b; if (memcmp (&pa1, &pb, sizeof pa1) == 0)
), then 3) do dereference the "illegal" pointer "legally" because it's the same bit-pattern as a "legal" pointer (*pa1 = 2
). Right? (Your edit ninja'd this comment...) – Auld&b
without saying&b
. It's a charade. – Pang