Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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?



> 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;
       ...
     }
     ...
  }


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?


What's your definition of "nothing bad happens"? And how do you recover if it does happen?




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: