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?
1 comment thread