Stack growth direction

So, from my previous memmove question, I would like to know how to find the direction of stack growth.

void stackDirection(int* i) { int j; if(&j>i) cout<<"Stack is growing up \n"<<endl; else cout<<"Stack is growing down \n"<<endl; } int main() { int i=1; stackDirtection(&i); } 
+6
c ++
source share
5 answers

The stack cannot grow up or down.

Each frame stack can be allocated at random points within the heap.
This is actually done on multiple operating systems to try and prevent malicious code from breaking the stack.

The concept of a stack growing towards the heap is just an easy way to teach the concept of a stack (and of course, the early implementations really worked in a way that was simple (no need to do something more complicated than you need when no one is trying to break you)).

+13
source share

Experiments like this are unreliable because you might run into exceptions. The optimizer may ruin your work, or the system may use registers for parameters. If you really need to know the direction of the stack, read the manual for your processor.

Despite this, if you are not writing an operating system or something really low level, if you need to know the direction of the stack, you are probably doing something ugly and terrible and should really rethink your methods.

+1
source share

Your function depends on the int * parameter, which can be specified anywhere, and also be NULL. It is better to compare the addresses of two local variables.

0
source share

This is beyond the scope of the C ++ standard. This is a specific implementation behavior and probably depends on the specific OS / processor architecture, etc.

It is better not to rely and not depend on such details if you are not involved in ETHICAL hacking :) and / or are not so much concerned about portability

0
source share

Consider the following correspondence, which provides one way the compiler can implement your code:

void stackDirection (int * i) {struct __vars_stackDirection {int j; } * __ stackframe_stackDirection = malloc (sizeof (int));

  if(&(__stackframe.j) > i) cout<<"Stack is growing up \n"<<endl; else cout<<"Stack is growing down \n"<<endl; 

} int main () {
struct __vars_main {int i; } * __ stackframe_main = malloc (sizeof (int));

  stackDirection(&(__stackframe.i)); 

}

You must agree that __stackframe_stackDirection and __stackframe_main will be essentially random. The stack can grow up or down.

Worse, you are assuming a lineup model. Either a<b, b<a, or a==b . But for pointers, this fails. All three comparisons a<b, b<a and a==b can be false at the same time.

0
source share

All Articles