A couple of days ago I noticed a link on del.icio.us popular to a list of programming interview questions from, allegedly, Google and Microsoft. Anyway, for the sake of having something to put up here, I’m going to post my solutions to a few…Hopefully someone will tell me if I’ve gone wrong along the way :)
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);
}

That said, perhaps there’s an easier way. I’m not aware of any standard tool which could tell me directly, though I wouldn’t be surprised if there were one. A bit of searching turned up a shell script which does the same thing but does the compilation for you, which is cute (but obviously OS dependent). Wikipedia tells me that most modern OSes grow the stack down which is odd given the security advantages of doing it up.

For what it’s worth, it goes down both on my Mac and a Linux box I have an account on. I’ll have to check Windows next time I have a chance.