how to correctly cast uint32_t to unsigned

607 views Asked by At

I'm trying to fix some C++ code with address sanitizer. The code says:

unsigned result = *(uint32_t*)data;

And the sanitizer gives:

runtime error: load of misaligned address 0x6280033f410a for type 'uint32_t', which requires 4 byte alignment

How do I need to fix this?

1

There are 1 answers

1
eerorika On BEST ANSWER
load of misaligned address 0x6280033f410a for type 'uint32_t' ...

How do I need to fix this?

You need to create an aligned object (such as a variable), and copy the content from the misaligned address:

std::uint32_t u32;
std::memcpy(&u32, data, sizeof u32);

This assumes that you intend to read sizeof u32 bytes from that address and that those bytes are ordered in native endianness.

how to correctly cast uint32_t to unsigned

Implicit conversion should be just fine:

unsigned result = u32;