typedef union epoll_data { void *ptr; int fd; __uint32_t u32; __uint64_t u64; } epoll_data_t;
Here int
and __uint32_t
are 4 bytes,while the others are 8 bytes.
When we set fd
to an int
,does it lie on the first 4 bytes or the last 4 bytes,or does it depend on endianness?
Some reason is appreciated.
When we declare a union, memory allocated for the union is equal to memory needed for the largest member of it, and all members share this same memory space. Since u is a union, memory allocated to u will be max of float y(4 bytes) and long z(8 bytes).
Each member of the union would be stored at the same address for that instance of the union. That's why you can only store one type of value in a union at the same time. Therefore, unions occupy the number of bytes required for the largest member.
A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.
But in union the size of detail is 32 bytes because the size of a union variable will always be the largest of its members.
The memories required for union1 and union2 is decided by the longest fields in them. The longest field in union1 is long type, 8-bytes cost. The longest field in union2 is long type, 8-bytes cost. So each of them takes 8 bytes memory spaces.
A typical memory layout of a running process. 1. Text Segment: A text segment , also known as a code segment or simply as text, is one of the sections of a program in an object file or in memory, which contains executable instructions.
Both struct and union are composite data structure but have different memory allocation strategy. In summary, struct need to store all the fields in the limited memory spaces as possible as it can. union will share the memory spaces between all fields, so sometimes you need an extra field to target that which type you would like to use.
Memory Layout of C Programs. A typical memory representation of C program consists of following sections. 2. 3. 5. 1. Text Segment: A text segment , also known as a code segment or simply as text, is one of the sections of a program in an object file or in memory, which contains executable instructions.
It lies on the first 4 bytes. From the C99 standard §6.7.2.1/14 (§6.7.2.1/16 in C11 and C18):
The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit-field, then to the unit in which it resides), and vice versa.
This implies that the address of all members of a union is the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With