Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to force memory alignment on pointer param in C?

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.

like image 380
cp.engr Avatar asked Oct 29 '22 13:10

cp.engr


2 Answers

No, there's nothing in the C or C++ standards that I know of that can force a pointer parameter to hold an appropriate value.

To get the memory, use posix_memalign:

#include <stdlib.h>

int posix_memalign(void **memptr, size_t alignment, size_t size);

DESCRIPTION

The posix_memalign() function shall allocate size bytes aligned on a boundary specified by alignment, and shall return a pointer to the allocated memory in memptr. The value of alignment shall be a power of two multiple of sizeof(void *).

Upon successful completion, the value pointed to by memptr shall be a multiple of alignment.

like image 87
Andrew Henle Avatar answered Nov 15 '22 07:11

Andrew Henle


For dynamic allocation, have a look at the standard (since C11) aligned_alloc.

For static allocation, I don't know of a standard method, so it'll be compiler dependent. For gcc eg., check the aligned attribute.

like image 25
Sander De Dycker Avatar answered Nov 15 '22 06:11

Sander De Dycker