2 ms·
Ok, here's the logic: 0. Your premise is that standard C does not require a runtime to provide any protection from stack memory growing into the heap. 1. Stan
by loeg 8y ago
Ok, here's the logic:
0. Your premise is that standard C does not require a runtime to provide any protection from stack memory growing into the heap.
1. Standard C defines automatic object storage and heap object storage.
2. It is implementation defined where heap objects are allocated in memory. As a result, the type and compatibility of arbitrary heap memory locations are unpredictable to developers.
3. It is implementation defined where stack objects are allocated in memory. As a result, the type and compatibility of arbitrary stack memory locations are unpredictable to developers.
4. Standard C says that mutated objects can't overlap [more or less].
5. Optimizing compilers don't allocate memory for stack objects that aren't at least partially mutated.
6. Standard C defines no way for developers to determine how deep their stack is, or where the top of the heap is.
7. From (2), (3), (5), (6), it is impossible for developers to determine whether or not they would violate (4).
8. As a result of (7) and (0), any use of both heap and stack objects is UB. A C runtime compliant to your definition in (0) could start the heap from 0x100, growing up, and the stack at 0x104, growing down.
8.a. Similarly, any use of static or other lifetime, and stack objects, is UB.
9. It logically follows from 8 that, under your premise (0), it is always UB to the stack and other kinds of data memory.
I guess you could make the case that the C committee hate everyone and all stack objects are UB.
But my read of the C standard is that the intent is that any use of stack objects is not in fact required to be UB. If stack objects were always UB, I think it would be called out explicitly or not specified in the standard.
So yes, I think any standard-conforming C implementation has to prevent stack clash one way or another. That could take the form of an alternate stack memory that is entirely separate from heap memory; it doesn't have to be probing and guard pages.
- saagarjha 8y ago> I guess you could make the case that the C committee hate everyone and all stack objects are UB. Honestly, I think that this is the logical conclusion, or at least, every compiler/machine implementation is subtly wrong; the standards glosses over what should happen when the stack is too large, for example, so technically any use of the stack is not guaranteed to be valid because you might just be out of space. The C standard is for a "head-in-the-clouds" abstract machine, so it doesn't concern itself with pedestrian issues like lack of memory.
- loeg 8y agoHeh, I guess that's possible. I hold out hope that it isn't the intent of the C committee, and maybe they'll consider firming up the stack memory model for C2x.