20130411

How to learn stack and flow of function call and control in cpp

/*How to learn stack. Stack is memory in which Last in first out is followed.
When function call is encountered the address of the next statement is stored or pushed in the stack. When the control returns back from the definition to calling function the address is poped out which is nothing but the statement next to the function call and executed.*/
#include<stdio.h>
#include<iostream>
using namespace std;
void function1();
void function2();

int main()
{
printf("1\n");
printf("2\n");
function1();
printf("3\n");
printf("4\n");

return 0;
}
void function1()
{
printf("1.1\n");
printf("1.2\n");
function2();
printf("1.3\n");
printf("1.4\n");
}
void function2()
{
printf("2.1\n");
printf("2.2\n");
}

/*
1
2
1.1
1.2
2.1
2.2
1.3
1.4
3
4
*/
/*
First 1 and 2 gets printed then function1 gets called and address of 3 gets stored instack.Now in inside function1 1.1 and 1.2 gets printed and function2 gets called and address of 1.3 gets stored in stack. Now inside function2 2.1 and 2.2 gets printed. Then as stack is LIFO so the last address ie of 1.3 was stored in stack so 1.3 followed by 1.4 is printed. Before the address of 1.3 address of 3 was stored in stack so now 3 and the next statement 4 gets printed
*/


Previous                             Home                               Next


2 comments:

  1. Stack:
    Stack is a container that stores other variables much like an array but with limited operation like insertion and deletion can be performed on top in LIFO, last in first out fashion.
    Stck Over Flow and Crash:
    As stack has limited size so it can store limited informations.Stack over flow happens when all the memory in stack has been allocated and crash happens as further allocations starts in other memory locations not allocated for that particular usr/program.

    ReplyDelete
    Replies
    1. CPP program to demonstrate stack over flow and crash:
      #include
      using namespace std;
      int main()
      {
      int array[10000000];
      return 0;
      }
      /Here large amount of memory(sizeof(int)*10000000) is requested which may not be available with the stack and program tries to allocate beyond stack memory may be from OS section which the program is not allocated causes crash of the application.*/

      Delete