Spread the love

Write down the program to tell whether the stack is growing in which direction in memory

The code you see here is compiler dependent (and also uses some nonstandard or  undefined features).

It is completely possible for a compiler to allocate specific stack space for each function and run the allocation backwards to the order in which the variables are declared.

So, in order reliably to determine which way the stack grows, you will need to call a function that uses the address of a variable in the calling function and then determine whether the address of the variable in the called function is less than or more than that of the calling function.

You can probably do it the opposite way by having the called function return the address of the variable in locals, but there are some compilers that deliberately prevent this (for good reason).

To check the direction of stack growth, we just declare two local variable in different scope and compare their address.

Program to tell  whether the stack is growing in which direction in memory

 

#include <stdio.h>

void stack(int *local_1)
{
	int local_2;
	
	printf("\n Address of local_2 : [%u]", &local_2);
	
	if(local_1 < &local_2)
	{
		printf("\n\n Stack is growing downwards.\n");
	}
	else
	{
		printf("\n\n Stack is growing upwards.\n");
	}
}

int main( )
{
	int local_1;
	
	printf("\n Address of local_1 : [%u]", &local_1);
	
	stack(&local_1);
	
	return 0;
}

 

Output

write-down-the-program-to-tell-whether-the-stack-is-growing-in-which-direction-in-memory

Suggested Reading

  1. C/C++ program to shutdown or turn off computer
  2. Write a C++ program to Make a Calculator
  3. TIC-TAC-TOE C++