I have a function in C which takes a uint8_t *
param, which must point to 32-bit aligned memory. Is it possible in C or C++, or with any particular platform's macros, to add some decoration to the parameter, such that the compiler or linker will throw an error at build time if it is not aligned as required?
The idea here is that I want to protect the function against improper use by other users (or me in 6 months). I know how to align the stuff I want to pass to it. I would like to ensure that no one can pass misaligned stuff to it.
Based on this answer, I think the answer to my question is "no", it's not possible to enforce this at build time, but it seems like a useful feature, so I thought I'd check. My work-around is to put assert((((size_t)ptr) % 4) == 0);
in the function, so at least I could trap it at runtime when debugging.
In my experience, results are undefined if you cast a misaligned uint8_t*
to uint32_t*
on many embedded platforms, so I don't want to count on the "correct" result coming out in the end. Plus this is being used on a realtime system, so a slowdown may not be acceptable.
Citations welcome, if there are any.