user148013 user148013 - 10 months ago 52
C Question

Does the stack grow continuously?

I'm wondering why this code isn't working as expected.

typedef char uint8;

int main(int argc, const char * argv[]) {
// insert code here...

uint8 number_1 = 3;
uint8 number_2 = 1;
uint8 *PointerToNumber = &number_1;

printf("%d \n", *PointerToNumber);
printf("%d \n", *PointerToNumber);

return 0;

This program prints 3 and -112. However shouldn't it print 3 and 1 if the stack grows continuously?

So if I'm pointing to number_1 and then increasing the pointer address of type uint8 shouldn't it then point to number_2 since it was declared right after number_2?

printf("%d \n", *PointerToNumber);

is cause for undefined behavior. It's pointless trying to justify any behavior. The behavior of the program could change with changes to optimization level, different compiler options, and a different compiler.

In this case, an optimizer could choose not to allocate any space for number_2 since it is not used in the function.