Re:Google interview questions - fun brain teasers
by huhtenberg on Monday August 04, 2008 @10:48PM
(#267089)
It is an obvious simplification, but his boss is wrong. The order of uninitialized variables can be changed by the compiler. For example to better package the variables due to an alignment requirements. E.g. allocating
char a;
long b;
char c;
short d;
on a RISC-style platform as "a,c,d,b" requires 8 bytes, while as a,b,c,d - 12. This may not matter in a majority of cases, but it some it does.
Re:Google interview questions - fun brain teasers
by aston on Tuesday August 05, 2008 @12:01AM
(#267129)
For homogenous variables (like two "int"s), I don't think you could make a strong argument for the compiler reordering them.
Re:Google interview questions - fun brain teasers
by huhtenberg on Tuesday August 05, 2008 @12:21AM
(#267146)
Some advanced optimization may benefit from this sort of reordering. Alternatively, a compiler that reorders all local variables for "security" purposes may mix even just two ints if it's implemented in a dumb way.
Re:Google interview questions - fun brain teasers
by tlrobinson on Monday August 04, 2008 @11:32PM
(#267115)
I was actually asked this problem on a job interview (not Google) and gave the answer your boss pointed out, but the interviewer then pointed out that local variables aren't necessarily laid out in memory in the order they're declared.
The function call is the only reliable way I can think of. Any others?
Re:Google interview questions - fun brain teasers
by huhtenberg on Tuesday August 05, 2008 @12:14AM
(#267140)
> Any others?
alloca()
Also, for the two-variable approach something like this should force the compiler to allocate variables in a required order:
int main()
{
int foo;
{
int bar;
...
}
...
}
Re:Google interview questions - fun brain teasers
by utnick on Monday August 04, 2008 @11:53PM
(#267123)
would this work?
in main: int x; int *p = &x; start writing random data to p, p-1, p-2, etc etc return; if nothing bad happens the stack grows up?
Re:Google interview questions - fun brain teasers
by aston on Tuesday August 05, 2008 @12:05AM
(#267131)
What's your definition of "nothing bad happens"? And how do you recover if it does happen?
Re:Google interview questions - fun brain teasers
by pfedor on Monday August 04, 2008 @10:11PM
(#267063)
Ummmm I may be way off base here but I remember hearing that some implementations (*BSD??) randomly reorder the local variables on stack to make exploiting buffer overruns more difficult. So if it's true then you do need to make a function call.
Also, the same answer basically works to implement "sizeof" for ints.