As stated in most of the answers before, it is perfectly safe to pass the pointer to func2()
in your special case.
In a real world piece of software however, I consider this harmful as you don't have control on what func2()
is doing with your variable. func2()
may create an alias to its parameter to use it asynchronously at a later point in time. And at that time, the local variable int i
may be gone when this alias is used later.
So from my point of view passing a pointer to a local (automatic) variable is extremely dangerous and should be avoided.
You may do so if you declare the variable in func1()
as static int i;
In that case, it is ensured, that the memory for i
won't get recycled and overwritten. However you will need to setup some Mutex locking for access control to this memory in a concurrent environment.
To illustrate this problem here is some code I just stumbled in yesterday while doing software testing at my customer. And yes, it crashes...
void func1()
{
// Data structure for NVMemory calls
valueObj_t NVMemObj;
// a data buffer for eeprom write
UINT8 DataBuff[25];
// [..]
/* Assign the data pointer to NV Memory object */
NVMemObj.record = &DataBuff[0];
// [..]
// Write parameter to EEPROM.
(void)SetObject_ASync(para1, para2, para3, &NVMemObj);
return;
}
void SetObject_ASync(para1, para2, para3, valueObj_t *MemoryRef)
{
//[..]
ASyncQueue.CommandArray[ASyncQueue.NextFreeEntry].BufferPtr = MemoryRef->record;
//[..]
return;
}
In this case, the data in the DataBuff
is long gone when the pointer in ASyncQueue.CommandArray[ASyncQueue.NextFreeEntry].BufferPtr
is used to store the data to the EEPROM.
To fix this code, it is at least necessary to declare static UINT8 DataBuff[25];
Additionally, it shall be considered to also declare static valueObj_t NVMemObj
as we don't know what the called function is doing with that pointer.
To put it briefly:
TL;DR
Even though it is legal in the C-language I consider it as harmful to pass pointers to automatic variables in a function call. You never know (and often you don't want to know) what exactly the called function does with the passed values. When the called function establishes an alias, you get in big trouble.
Just my 2 cents.