Question

How could you confirm that "the stack" that local variables are stores on grows downwards? (C++)

How could you confirm that "the stack" that local variables are stores on grows downwards? (C++)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Stack can grow downward/upward depending on environment for which code is compiled.
Generally stack grows down from high memory, and the heap grows upwards from low memory, so they will never collide each other but there are some cases in which stack goes upwards.


To check whether the stack grow upwards or downwards we can write a program and understanding a certain condition which will help us to find whether our stack goes upwards or our stack goes downward.

If there's a variable which is created in a function compared to a variable which is coming from the main has lesser address it means stack grows downwards.

In short if main function address us greater than local function it means that stack grows downwards.

The stack grow downward so that program can be compiled in a low memory address, and the stack with the remaining memory. Stack initialization could be performed before program load, simplifying programs.

CODE:


#include <iostream>
#include <string>
using namespace std;
void check(int *mainVar)
{
int temp;
if (mainVar < &temp) // & is used for address
cout<<"Stack grows upwards"<<endl;
else
cout<<"Stack grows downwards"<<endl;
}
  
int main()
{
// fun's local variable
int mainVar;
  
check(&mainVar); // mainVar address is passed to the function
return 0;
}

OUTPUT:

CODE:

WHEN EVER A VARIABLE IS CREATED IN A FUNCTION IT WILL ALWAYS HAVE A LESSER THAN MAIN FUNCTION ADDRESS CONFIRMING THAT IT STACK FOR LOCAL VARIABLES IN C++ GOES DOWNWARDS

IF YOU HAVE ANY QUERY PLEASE COMMENT DOWN BELOW
PLEASE GIVE A THUMBS UP

Add a comment
Know the answer?
Add Answer to:
How could you confirm that "the stack" that local variables are stores on grows downwards? (C++)
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT