0

Possible Duplicates:
stack growth direction
Does stack grow upward or downward?

Hi all,

How would I find out if a machine’s stack grows up or down in memory in C. More importantly, which is better: a system in which the stack grows up or one in which a stack grows down ?

And will below logic work ???

void sub(int *a) 
{
int b;

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

I mean this expression is valid in C

if (&b > a) 
Community
  • 1
  • 1
Amit Singh Tomar
  • 8,380
  • 27
  • 120
  • 199

1 Answers1

6

Stacks don't even have to exist in the first place, and when they do, they don't have to work in the way you expect. They can be created dynamically, for example, or they could just jump around in memory. Your question isn't really a pure "C" question, because it isn't portable.

However, assuming that stacks either grow up or grow down, then you can just check this by taking the address of a variable inside a caller function and also inside a callee, and checking to see which one is greater; it's straightforward.

user541686
  • 205,094
  • 128
  • 528
  • 886