Monday, April 12, 2010

Stack direction

From: http://kstruct.com/2007/04/16/interview-questions-stack-direction/

Stack Growth : How would you find out if a machine’s stack grows up or down in memory?

Well, it’s fairly simple to write a C program to test this. Obviously I’m assuming that a C compiler is available. The following program creates an integer (a) on the stack, then passes a pointer to a down to the function sub. sub creates another integer on the stack (b), then compares the address of a to the address of b. If b’s address is greater then a’s, then the stack is growing up, if it’s less, then it’s growing down.

#include <stdio h>

void sub(int *a) {
int b;

if (&b > a) {
printf("Stack grows up.");
} else {
printf("Stack grows down.");
}
}

main () {
int a;
sub(&a);
}

No comments: