I've one struct declared as above
struct foo {
void * elem;
};
I want to manage the free() of elem in this struct, but I don't know which is the type of the elem, so I'm making a void *
to manage all data types.
Is it safe to assign to foo.elem a pointer to a local variable?
For example, are these methods safe?
// Method 1
struct foo * get_foo() {
int a = 10;
struct foo x = malloc(sizeof(struct foo));
x.elem = &a;
return x;
}
// Method 2
void get_foo(struct foo x) {
int a = 10;
x.elem = &a;
}
Regardless of the validity of your code examples as exemplars of what you are asking about (neither illustrates the question correctly), it is never valid or safe to retain a pointer to a variable outside of the lifetime of that variable.
Dereferencing such a pointer is undefined behaviour, in principle anything could happen. In practice what does happen is the memory for that variable becomes available for reuse and if you read it via the pointer it may no longer contain the same value, and if you write it, you may be modifying some unrelated data object or corrupting the call stack - the behaviour in either case is non-deterministic; which is no more useful that undefined behaviour.
Note that it is an issue of lifetime not of scope. A pointer to a local static
is valid.