Maybe it’s a newbie question, but is there a method in C/C++ to prevent a function from accepting a pointer to a local variable?
Consider this code:
int* fun(void)
{
int a;
return &a;
}
The compiler will generate a warning that the pointer can not be returned. Now consider this:
int* g;
void save(int* a)
{
g = a;
}
void bad(void)
{
int a;
save(&a);
}
This will pass through the compiler without a warning, which is bad. Is there an attribute or something to prevent this from happening? I.e. something like:
void save(int __this_pointer_must_not_be_local__ * a)
{
g = a;
}
Thanks in advance if someone knows the answer.
No, there is no reliable and portable way to tell a pointer to local from a pointer to a heap object. There is no way to declaratively prevent this, either.
There are hacks dependent on the memory layout of your particular system that work at runtime by invoking unspecified behavior (see this answer for an example), but you are on your own if you decide to give them a try.