Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copying over data from a union in C

Tags:

c

pointers

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.

like image 811
Julian Avatar asked Jan 13 '13 06:01

Julian


People also ask

What is Union in C with example?

Union in C. Like Structures, union is a user defined data type. In union, all members share the same memory location. For example in the following C program, both x and y share the same location.

How are members of a union stored in C++?

The members of a union are stored in a shared memory area. This is the key feature that allows us to find interesting applications for unions. Consider the union below: There are two members inside this union: The first member, “word”, is a two-byte variable. The second member is a structure of two one-byte variables.

What type of data can be used inside a union?

You can use any built-in or user defined data types inside a union based on your requirement. The memory occupied by a union will be large enough to hold the largest member of the union. For example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string.

How many bytes are allocated in a union?

Consider the union below: There are two members inside this union: The first member, “word”, is a two-byte variable. The second member is a structure of two one-byte variables. The two bytes allocated for the union is shared between its two members. The allocated memory space can be as shown in Figure 1 below.


1 Answers

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?

like image 99
Alok Save Avatar answered Sep 28 '22 23:09

Alok Save