Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a byte array to a struct pointer depends on endianness or memory alignment?

Suppose this code:

unsigned char list[3] = { 1, 2, 3 };
struct _struct{
  unsigned char a;
  unsigned char b;
  unsigned char c;
} *s;
s = ( _struct * ) list; 

Can I assume that always s->a == 1, s->b == 2, s->c == 3 ?
Or it will depend on the system's endianness or memory alignment?

like image 354
Petruza Avatar asked Jun 02 '10 19:06

Petruza


People also ask

Does Endianness affect array order?

Note: Endianness does NOT affect ordering of array elements! In the previous example, the elements were just 1 byte each. Here, we see that the order of the elements of the array is the same on both systems, but the ordering of the bytes for those elements is different.

How does struct padding work where are the extra bytes stored in memory?

structure AThe compiler will insert a padding byte after the char to ensure short int will have an address multiple of 2 (i.e. 2 byte aligned). The total size of structa_t will be sizeof(char) + 1 (padding) + sizeof(short), 1 + 1 + 2 = 4 bytes.

How many bytes is a pointer to a struct?

Pointers are always the same size on a system no matter what they're pointing to (int, char, struct, etc..); in your case the pointer size is 4 bytes.

What is structure padding structure alignment reason for structure padding?

Structure padding is a concept in C that adds the one or more empty bytes between the memory addresses to align the data in memory. Let's first understand the structure padding in C through a simple scenario which is given below: Suppose we create a user-defined structure.


2 Answers

Let's dissect this.

In all cases, sizeof(char) == 1, and the list array will have its three members at memory locations list, list + 1, and list + 2.

The situation with the struct is not quite as clear. The Standard guarantees that the members will be allocated in increasing memory locations, but not that they will be contiguous. The compiler is free to introduce padding between members, and padding at the end.

Therefore, s->a == 1 will always be true. If the implementation puts the unsigned chars in the struct adjacent (and most will), then the other equalities will necessarily be true.

By the way, calling a struct _struct may cause problems. A name beginning with an underscore in the global namespace is reserved for the implementation.

like image 114
David Thornley Avatar answered Oct 10 '22 18:10

David Thornley


Yes, it will depend on the system's and compiler's memory alignment and packing rules.

like image 45
Oliver Charlesworth Avatar answered Oct 10 '22 19:10

Oliver Charlesworth