Bloomberg LP Interview Question
Software Engineer / DevelopersCouldn't the compiler arbitrarily reorder the order of local variables on the stack frame?
I'd think the way to do this would be:
#include <stdio.h>
void g(int* pi)
{
int j;
printf("g(): address of j: %p\n", &j);
if (&j > pi)
{
printf("stack grows up\n");
}
else
{
printf("stack grows down\n");
}
}
void f()
{
int i;
printf("f(): address of i: %p\n", &i);
g(&i);
}
void f1()
{
int i;
int j;
printf("f1(): address of i: %p\n", &i);
printf("f1(): address of j: %p\n", &j);
if (&j > &i)
{
printf("stack grows up\n");
}
else
{
printf("stack grows down\n");
}
}
int main(char** pszArgs, int cArgs)
{
f();
f1();
}
With gcc, both result in "stack grows down".
I think the order of local variables on the stack (f1 from the code above) is implementation dependent. Correct me if I'm wrong.
At the very least my solution will work because we're adding a stack frame. Without some kind of fancy whole program optimization it should give the correct answer.
/* To show if the stack is increasing or decreasing */
#include<stdio.h>
void f1();
void f2();
void f3();
void main()
{
int a =1;
printf("The address of a is %d \n", &a);
f1();
int c = 5;
printf("The address after f1 and f2 has finished is %d \n", &c);
}
void f1()
{
int b= 2;
printf("The address of b is %d \n", &b);
f2();
}
void f2()
{
int c = 3;
printf("The address of c is %d \n", &c);
}
call a function with variable recursively. that shoudl solve it.
- ani August 26, 2007normally its always a stack which grows down , heap grows up,
may be that is why we have stack underflow and buffer overflow :)