Variables can be allocated in the stack heap or statically W
Variables can be allocated in the stack, heap, or statically. What accounts for these differences (e.g.,
performance)? Give an example C++ routine that would not work correctly if local variables are
allocated statically.
Solution
Stack:
A stack is special region of CPU where the temporary variables created by the functions are stored.
The variables of a function are generally stored in a stack.
stack is maintained and optimized by the CPU
Whenever a function declares a variable it is pushed on to stack.
when the function exits, all the variables created by that function are poped from the stack.hence they are permanently destroyed.
Static Variables:
Variables of the stack can be kept in the memory even the function that created it exits by using static keyword before that variable.
static varibles are also visible only within the function that created it.
Heap:
When you want to store a variable in a heap it need to be created using malloc() and calloc()
you need to free the memory allocated to heap variables using free()
Differances:
1)stack is very fast to acess , Heap is relatively slow to acess
2)stack variables have local scope, static stack variables have global acess but are available within the function, heap variables have global scope
3)The size of stack is limited, In Heap there is no limit on memory size.
4)the variables cannot be resized in stack, in heap variables can be resized
5)In stack you need not maintain memory, in heap you should maintain the memory
Example:Program to check whether the number is given numbers are pallindromes or not
#include<iostream.h>
public int pallindrome(int num)
{
int digit;
static int rev=0;
do
{
digit = num % 10;
rev = (rev * 10) + digit;
num = num / 10;
} while (num != 0);
return rev;
}
int main()
{
int num,r,ch,n;
do
{
cout<<\"Enter a positive number: \";
cin>>num;
n = num;
r=e.pallindrome(num);
if (n == r)
cout<<\" The number is a palindrome\";
else
cout<<\" The number is not a palindrome\");
cout<<\"\ do you want to check for other number(1:yes\ 2:no)\ enter appropriate number\";
cin>>ch;
}
while(ch==1);
}
Sample Output:
Enter a positive number:
121
The number is a palindrome
do you want to check for other number(1:yes
2:no)
enter appropriate number
1
Enter a positive number:
121
The number is not a palindrome
do you want to check for other number(1:yes
2:no)
enter appropriate number 2
-->The program gives expected result when we enter first number to check.
but when we want to check for more numbers the program will not work as expected. this is because the variable rev is declared as static so it retains its value and when the next time pallindrome function is called insted of creating rev and assiging \'0\' to it, the previous value will be used. Thus resulting in unexpected results.
-->If we did not declared rev as static the program will work as expected

