So from my previous memmove question I would like to know how to find direction of stack growth.
void stackDirection(int* i)
{
int j;
if(&
The stack may not grow up or down.
Each stack frame can potentially be allocated at random points inside the heap.
This is actually done in several OS to try and prevent stack smashing by malicious code.
The concept of a stack growing towards the heap is just an easy way to teach the concept of a stack (and of course early implementations did work this way as it was simple (no need to make something harder than you need when nobody is trying to break you)).
Your function depends on int* parameter which can point to anywhere, and also be NULL. It is better to compare addresses of two local variables.
Experiments such as this are unreliable, because you can run into exceptions. The optimiser can mess you up, or the system might use registers for parameters. If you really must know the stack direction, read the manual for your processor.
Notwithstanding that, unless you are writing an operating system or something really low-level, if you need to know the stack direction you are probably doing something ugly and horrible and should really reconsider your methods.
This is outside the scope of the C++ standard. It an implementation defined behavior and probably depends on the specific OS/processor architecture etc.
It is best not to rely or depend on such details, unless you are into ETHICAL hacking :) and / or not so much concerned with portability
Consider the following rewrite, which exposes one way in which a compiler may 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'll have to agree that __stackframe_stackDirection
and __stackframe_main
will be essentially random. The stack can grow up or down.
Worse, you are assuming a lineair model. Either a<b, b<a, or a==b
. But for pointers this does not hold. All three comparisons a<b, b<a and a==b
may be false at the same time.