Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 630
  • Last Modified:

How to determine stack grows upward or downward?

Given a machine with an unknown architecture and a C compiler, how can we determine if stack grows upward or downward?
0
luoys
Asked:
luoys
  • 3
1 Solution
 
PaulCaswellCommented:
Hi luoys,

void main ( int argc, char * argv [] )
{
 char * a;
 char * b;
 printf ( "Stack grows %swards!\n", (a<b)?"up":"down");
}

Paul
0
 
jhanceCommented:
This assumes, does it not, that the complier creates objects on the stack in the order in which they appear in the source code?  While that's probably a good assumption in most cases, I'd turn off any compiler optimization options before trying this test.
0
 
PaulCaswellCommented:
Good point!

This migh be better then:

int StackGrowsUp ( void * a )
{
 char * b;
 return ( b > a );
}

void main ( int argc, char * argv [] )
{
 char * a;
  printf ( "Stack grows %swards!\n", (StackGrowsUp(&a))?"up":"down");
}

0
 
steveiamCommented:
I'm a bit vague on this, so don't take my comment as definitely accurate, but would "stack frames" confuse the test suggested by PaulCaswell's second code example?  If its creating a completely new stack frame for the called function (StackGrowsUp), then it could be anywhere in memory, rather than immediately above/below the one for main()? (or have I misunderstood stack frames??)
0
 
PaulCaswellCommented:
Hi steveiam,

Stack frames are areas of the stack specifically allocated by functions to hold their local parameters and a return address. They are also, therefore, allocated on the stack and so obey the same lifo nature and thus will maintain the stack's direction.

Paul
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now