Why does C++ disallow the creation of valid pointers from a valid address and type?


New Member
If you know two pieces of information:
  1. A memory address.
  2. The type of the object stored in that address.
Then you logically have all you need to reference that object:
#include <iostream>
using namespace std;

int main()
    int x = 1, y = 2;
    int* p = (&x) + 1;
    if ((long)&y == (long)p)
        cout << "p now contains &y\n";
    if (*p == y)
        cout << "it also dereference to y\n";
However, this isn't legal per the C++ standard. It works in several compilers I tried, but it's Undefined Behavior.

The question is: why?


Thành viên BQT
It wreaks havoc with optimizations.
void f(int* x);

int g() {
    int x = 1, y = 2;
    return y;
If you can validly "guess" the address of y from x's address, then the call to f may modify yand so the return statement must reload the value of y from memory.

Now consider a typical function with more local variables and more calls to other functions, where you'd have to save the value of every variable to memory before each call (because the called function may inspect them) and reload them after each call (because the called function may have modified them).