I have the struct:
struct mystruct {
int a;
};
If I create a function with the struct as an argument, and try to directly return its address:
struct mystruct *
modifystruct1(struct mystruct s)
{
s.a = 5;
return &s;
}
Compiling with c99 -Wall -Wextra -pedantic
will warn warning: function returns address of local variable [-Wreturn-local-addr]
,
which I know I shouldn't do.
However, if I save the address to another variable and try to return that, the warning disappears:
struct mystruct *
modifystruct2(struct mystruct s)
{
struct mystruct *sptr = &s;
sptr->a = 5;
return sptr;
}
Is this okay to do, or is it no different from the above? (and if so, why is there no more warning?)
If not, how can I modify a copy of a struct inside a function
and return a pointer to that struct,
safely, preferably without using malloc
?
Is this okay to do, or is it no different from the above? (and if so, why is there no more warning?)
In fact it is the same. After exiting the function
struct mystruct *
modifystruct2(struct mystruct s)
{
struct mystruct *sptr = &s;
sptr->a = 5;
return sptr;
}
the returned pointer will be invalid because it points to a local variable s
with automatic storage duration that is not alive after exuting the function.
It seems the compiler is unable to determine that the returned pointer sptr
points to a local object.
Pay attention to that the function parameter does not make sense because it is at once changed within the function.
If you want to change the object of the structure type passed to the function then pass it by reference through a pointer it it like
void modifystruct2(struct mystruct *s)
{
s->a = 5;
}
If you want to create an object of the structure type within the function and to return it then define the function for example the following way
struct mystruct modifystruct2( void )
{
struct mystruct s = { .a = 5 };
return s;
}