Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program to find direction of stack growth

Tags:

c

stack

How do I find in C whether a stack is progressing in forward or reverse direction ? WIll this work?

int j = 0;
int k = 0;

if (&k > &j) 
 printf ("Stack is growing in forward direction");

else if (&k < &j) 
  printf ("Stack is growing in reverse direction");
like image 554
Neel Avatar asked Nov 27 '22 14:11

Neel


2 Answers

To be reliable, one would have to find the difference between two function calls.

void func(int *p) {
    int i;
    if (!p)
        func(&i);
    else if (p < &i)
        printf("Stack grows upward\n");
    else
        printf("Stack grows downward\n");
}

func(NULL);

Note that this won't give you an answer about C, but about your compiler.

like image 140
ikegami Avatar answered Dec 17 '22 04:12

ikegami


You cannot. In your code, (&k > &j) invokes undefined behavior behavior. Pointer comparison with relational operators is not defined unless the pointers point to objects within the same array (or one object beyond the end of the array).

Whether a stack exists is dictated by your implementation. Undefined behavior cannot predict implementation details.

The ISO C standard does not mention the word "stack" even once. A stack might not even exist. The memory used by function invocations to keep local variables might not even be contiguous.

like image 38
sigjuice Avatar answered Dec 17 '22 04:12

sigjuice