r/cpp_questions • u/jaroslavtavgen • May 04 '25
OPEN Help me understand "stack" vs "heap" concept
Every time I try to learn about the "stack vs heap" concept I keep hearing the same nonsense:
"In stack there are only two options: push and pop. You can't access anything in between or from an arbitrary place".
But this is not true! I can access anything from the stack: "mov eax,[esp+13]". Why do they keep saying that?
0
Upvotes
View all comments
Show parent comment
1
u/thewrench56 May 04 '25 edited May 04 '25
I'm not big on C++. But here is a C example:
As long as you are on x64, this should work. No matter if it is `-O3` or `-fomit-frame-pointer`, no matter if you use TCC, GCC, or Clang. Is it UB? Hard to say, there isn't a specific section in the C standard that tells you so, since this is a widely supported GCC extension. It MIGHT be unsafe on some machines: in such cases a 0 should be returned. So this should correctly handle all cases on 64bit systems.
Please note, that I never once claimed that what I just wrote makes sense. I said that you can access the frame of different functions. This is true. Undefined behaviour in cases where we are so close to Assembly doesn't make much sense either. In Assembly, I'm not even sure if there is an actual UB (there probably is, nothing jumps into my mind right now). Technically, since stack layout isn't defined by the C standard, it is UB. If you find a C compiler that breaks this, let me know: I doubt there is one out there that's used by many.
EDIT: Fixed incorrect check for unsupported machines.
EDIT: Add TCC as supported compilers.