4 ms·
> This is because declaring the variable x means it must have some associated storage I've not read the C spec, so I may be terribly wrong here, but I'm incli
by agalunar 6y ago
> This is because declaring the variable x means it must have some associated storage
I've not read the C spec, so I may be terribly wrong here, but I'm inclined to disagree: x is not accessible outside of a() and cannot be read or modified by another part of the program, and so a compiler would be perfectly justified in not bothering to allocate storage for it.
> To permit this basic optimization, you need to have to some sort of rule that allows you to reason that a value whose address is never taken can never be legally accessed by a pointer.
Essentially, I'm contending that not only is the address of x never taken, it never can be taken, and therefore the optimization is safe.
(In practice, if x did happen to have stack space allocated for it and you knew what location it ought to have relative to the stack pointer, you could modify x. But insofar as I'm aware, C does not guarantee many things about the layout of memory or a particular calling convention anyway, and so you shouldn't rely on this. And that isn't changed by one's model of pointers.)
- bzb5 6y agoWhat if the thread is preempted between the two lines? Another thread should be able to read and modify that variable, no?
- asdfasgasdgasdg 6y agoFor C standards before C11, C doesn't have a thread-aware memory model. The notion of threads suspending and waking up, or memory access from one thread's stack to another, does not exist in the standard, at least as far as I'm aware. The C standard also doesn't define the memory layout of the stack, so there is no standard way to acquire the address of that variable. It's easy enough to see that compilers do not actually create storage for it: https://godbolt.org/z/cfE9o5 https://godbolt.org/z/cfE9o5 In C11 there is a thread aware memory model, but still no standard way to access that location, so compilers will assume it doesn't need to be created. https://godbolt.org/z/KTz9sT https://godbolt.org/z/KTz9sT
- mhh__ 6y agoIn what language is it defined behaviour to grab a thread and start playing with its memory? The compiler can only know what the standard says and in this case it would be fair game