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

Peal

New Member
#1
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:
Mã:
#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?
 

Admin

Administrator
Thành viên BQT
#2
It wreaks havoc with optimizations.
Mã:
void f(int* x);

int g() {
    int x = 1, y = 2;
    f(&x);
    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).
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top