JohnAnge Kernodle
JohnAnge Kernodle

Reputation: 259

Are a functions local variables always stored in the same set of memory locations every time it executes?

I'm assuming no but not positive. Not sure If other variables can take up the same spot in the stack.

Upvotes: 3

Views: 783

Answers (2)

fullstackdev
fullstackdev

Reputation: 535

The compiler will generate code to assign memory addresses based on a "stack pointer" address + offset. So, the actual physical address for each local will vary on each invocation of the function. The offset may well be the same each time because the compiler code gen logic will be the same. The stack pointer address is likely to be different based on what else gets executed before the next invocation of the function.

Upvotes: 2

John3136
John3136

Reputation: 29265

No. A function's local variables are not always at the same address.

Consider a recursive function. If the local variables were supposed to be in the same place, all their values would have to be copied in and out each time you went in and out of recursion.

The normal way of doing it is that each function call has a "block" on the stack. If you call the same function twice in a row the local variable addresses will probably be the same. If you call it recursively the second call will be in a different area of stack and so the local variable addresses will be different.

Upvotes: 6

Related Questions