Apple Interview Question
Software Engineer / DevelopersTeam: Data Mining
Country: United States
I dont think you can return the address of the local variable. That variable will be popped out and the memory location will be freed..
stack and heap are memory used for allocation by programs. A program has:
1. code
2. heap
3. stack
4. BSS
5. data (global and static data)
stack is used for storage of auto variables in program. When a program starts in main() all the auto variables are stored in stack using LIFO algo. Stack can grow down or UP depending on the system being used.
example code taken from other site :)
debug this program and see how memory is being allocated, this will give you a fare understanding of how stack works.
This program will give error, because in "fn()" we eat up the memory assigned to "i" and when fn() finishes that memory is freed. But we try to print "i' which has already been freed.
#include <iostream>
using namespace std;
void fn(void)
{
int * ptr;
ptr = (int *)&ptr;
++ptr;
int* mainfp = (int*)(*ptr);
--mainfp;
--mainfp;
*mainfp = 20;
return;
}
int main (void)
{
int i = 10;
fn();
cout<<”I =<<i<<endl;
return 0;
}
void function f()
{
int p=0, q=0;
int *add_p =NULL, *add_q=NULL;
add_p = &p;
add_q = &q;
if(add_p > add_q) {
/* p higher on stack */
printf("Downward growing");
} else {
printf("Upward growing");
}
I think this is the way easier way to tell if the stack is growing upwards or downwards...
Idea--
1. I am declaring a variable in main function and storing it's address
2. Then i call a function from main and declare a variable there store this address in another variable.
3. Based on the values of addresses i can easily tell whether the stack is growing upwards or downwards.
- Best Answer April 17, 2012