Suppose I have a function that declares and initializes two local variables – which by default have the storage duration auto
. This function then calls a second function, to which it passes the addresses of these two local variables. Can this second function safely use these pointers?
A trivial programmatic example, to supplement that description:
#include <stdio.h>
int adder(int *a, int *b)
{
return *a + *b;
}
int main()
{
auto int a = 5; // `auto' is redundant; included for clarity
auto int b = 3;
// adder() gets the addresses of two auto variables! is this an issue?
int result = adder(&a, &b);
printf("5 + 3 = %d\n", result);
return 0;
}
This program works as expected, printing 5 + 3 = 8
.
Usually, when I have questions about C, I turn to the standard, and this was no exception. Specifically, I checked ISO/IEC 9899, §6.2.4. It says there, in part:
4 An object whose identifier is declared with no linkage and without the storage-class specifier
static
has automatic storage duration.5 For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way. (Entering an enclosed block or calling a function suspends, but does not end, execution of the current block.) If the block is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate. If an initialization is specified for the object, it is performed each time the declaration is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached.
Reading this, I reason the following points:
Variables
a
andb
have storage durationauto
, which I've made explicit using theauto
keyword.Calling the
adder()
function corresponds to the parenthetical in clause 5, in the partial quote above. That is, entering theadder()
function "suspends, but does not end," the execution of the current block (which ismain()
).Since the
main()
block is not "end[ed] in any way," storage fora
andb
is guaranteed. Thus, accessing them using the addresses&a
and&b
, even insideadder()
, should be safe.
My question, then, is: am I correct in this? Or am I just getting "lucky," and accessing memory locations that, by happenstance, have not been overwritten?
P.S. I was unable to find an exact answer to this question through either Google or SO's search. If you can, mark this as a duplicate and I'll delete it.