7

I've got a pointer to a struct with a union

so let's say we have

struct A {
  union {
    char **word;
    struct A *B
  } u;
};

and I have variables x and y of type A*

typedef A* A_t;
A_t x;
A_t y;

would x->u = y->u be enough to copy over stuff in the union.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
Julian
  • 483
  • 1
  • 6
  • 17

1 Answers1

5

You cannot just dereference pointers if they are not pointing to anything valid.
To be able to do x->u you have to make sure x points to some valid memory, The code you show dereferences an uninitialized pointer which causes an Undefined Behavior and most likely a crash. Same applies for y->u. So make sure x and y point to valid memory before you dereference them.

x->u = y->u

Will not perform a deep copy but a shallow copy.
You will basically end up with two pointers pointing to the same memory, which is not probably what you intend or need.

If you need a deep copy, you should allocate your destination enough memory to hold the data being copied to it and then use memcpy to copy the contents of the source union to it.

Good Read:
What is the difference between a deep copy and a shallow copy?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 1
    He'd better allocate some space for x and y to point to, first. – Carl Norum Jan 13 '13 at 06:31
  • @CarlNorum: Hmm, Ofcourse, I assumed OP would do so.Anyways since you brought it up I will add a note about it. – Alok Save Jan 13 '13 at 06:35
  • 1
    This answer is not correct. Assuming all pointers are initialized correctly, x->u = y->u really is "enough to copy over stuff in the union", the "stuff in the union" being either a pointer-to-pointer-to-char or pointer-to-struct-A. This has the same effect as memcpy(&x->u, &y->u, sizeof(x->u)); Of course, whatever the relevant pointer points to will not be touched or copied and that's not what was asked. – nattgris Apr 14 '21 at 16:24