Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting pointer types on different architectures

I have the following structure and "getter" function that returns a cast to an unsigned integer:

struct s {
    uint32_t a;
};

void get_a(struct s *st, unsigned *ret)
{
    *ret = (unsigned)st->a;
}

The following code is run:

struct s st;
uint16_t x;

st.a = 1;
get_a(&st, (unsigned *)&x);

And for x86_64, i686, armv7hl, ppc64le and other architectures x == 1, but for ppc64 x == 0. Why is this? Little- vs. big-endian?

like image 265
MC93 Avatar asked Jul 24 '15 10:07

MC93


People also ask

Can a pointer be cast to another type in C?

Type Casting Of Pointers in C. We saw that pointer values may be assigned to pointers of same type. However, pointers may be type cast from one type to another type. In the following code lines, A is an int type variable, D is variable of type double, and ch is a variable of type char.

Should students be careful while type casting pointers?

The inference is that students should be extremely careful while type casting pointers. Dinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog.

What are the three pointers to the value 150?

After the execution of the above code all the three pointers, i.e., Pa, Pd, and Pc, point to the value 150. Note the difference between the type casting of a variable and type casting of a pointer. Taking the above declarations of A, D, ch of the type int, double, and char, respectively. For type casting of D into type int, the code is

What is casting in the C language?

In the C language, casting is a construct to view a data object temporarily as another data type. Figure 1. ILE C Source to Show IBM i pointer casting


1 Answers

The problem is that you have:

uint16_t x;

but then you try to write to that memory location as if it were the location of unsigned.

If you were on a system where unsigned and uint16_t are the same type, this is fine. But on other systems, such as the one you used for your code sample, you are in trouble.

First of all, this causes undefined behaviour by violating the strict aliasing rule. Variables of type uint16_t may only be written to through lvalues of type uint16_t, or a character type.

But even if it did not violate strict aliasing, you would still cause UB by writing outside the bounds of x. Probably, you are writing 4 or 8 bytes into a 2-byte memory location, so it will overflow the buffer.

There could also be UB if x is not correctly aligned for unsigned.

like image 67
M.M Avatar answered Oct 10 '22 04:10

M.M