Home > Net >  Is an external void pointer to a local variable safe?
Is an external void pointer to a local variable safe?

Time:04-17

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;
}

CodePudding user response:

The first doesn't compile. It's not safe code, in the sense that it's not code at all.

The second just uselessly modifies local variable x. It's safe, since it effectively does absolutely nothing, and there's nothing inherently harmful about doing nothing.

CodePudding user response:

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.

Strictly it is undefined behaviour so 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.

  • Related