Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Behavior of Pointer Arithmetic on the Stack
Post
Behavior of Pointer Arithmetic on the Stack
Consider the following code:
#include <stdio.h>
int main() {
int a = 5;
int b;
++*(&b + 1);
printf("%d\n", a);
return 0;
}
The output is as expected:
6
By creating and incrementing a pointer to b
, I'm able to access a
, since b
is below a
on the stack. Is this behavior guaranteed by the C language, or is this undefined/unspecified behavior? If UB, what does the standard have to say that disallows this? For example, does C guarantee that the stack grows downwards, or that arithmetic with pointers into the stack is valid?
This is absolutely undefined behavior. The C standard doesn't say anything about stacks or how they should behave or …
2y ago
Generally speaking, pointer arithmetic is undefined behavior unless carried out on arrays. This is how the additive oper …
2y ago
I'm able to access a, since b is below a on the stack. No, it's not! You have no guarantee in what order the compi …
2y ago
Not only does the C language not guarantee it, it also will fail on actual compilers, as soon as you enable optimisation …
2y ago
1 comment thread