4 ms·
> Any pointer which points to that integer value can then observe its value With a() as written, there's no legitimate way to obtain the address of x, so there
by robotresearcher 6y ago
> Any pointer which points to that integer value can then observe its value
With a() as written, there's no legitimate way to obtain the address of x, so there is no such pointer.
Am I wrong about this?
- sanxiyn 6y agoYes. If pointers are integers, you can cast an integer (let's say 1234) to a pointer, which happens to be the address of x. It is a legitimate way to obtain the address of x if pointers are integers, so compilers must assume this can possibly happen.
- robotresearcher 6y agoSure, but you can't know what that number is. It's almost certainly not 1234, and since it's an auto allocated var with local scope, it's probably on the stack unless it's been optimized elsewhere, so it's dynamic, and exists only for the lifetime of each run of a(). You might figure out some evil way to get it for some implementation, but I don't think the C spec gives you a reliable way. That's what I mean by 'legitimate'. Even if you modified the code of a() to pass out the address of x to a caller, they can't safely use that pointer and the actual behavior is undefined. x does not exist outside of a call to a().
- sanxiyn 6y agoI think you are right there is no reliable way, but C specification does not disallow unreliable programs. It only disallows nonconforming programs. Compilers can't optimize a() to b() under pointers-are-integers model. It may be linked to code like c(): void c() { int random = generate_random_number(); int* address = (int*)random; *address = 4; } In real machines, c() randomly overwrites memory with 4, in particular memory of x whose value will change from 5 to 4. In C abstract machine, c() randomly overwrites memory with 4, but it can never overwrite memory of x, because memory of x does not have integer address. Therefore compilers can optimize a() to b().
- dooglius 6y agoYou can "obtain the address", whatever that means, but that does not mean it's well-defined behavior to change the data in said address.
- sanxiyn 6y agoThe whole point of OP's proposal is that it should be well-defined, because "pointers are easy". I am trying to demonstrate how absurd that is.
- dooglius 6y agoI think you are taking an overly strong reading, I highly doubt the author would say that writing to stack memory is reasonable unless the address has explicitly been taken with &x
- ByteJockey 6y agoSure, but integers are passed by copy in C. Obtaining an integer is not a reason to think you can access the original memory address. Unless you return a reference to an integer that's been malloc'd.