Is forced memory alignment in a pointer parameter in C?

I have a function in C that takes a parameter uint8_t *that should point to 32-bit aligned memory. Is it possible in C or C ++ or using any specific platform macros to add some decoration to a parameter so that the compiler or linker gives an error during assembly if it is not aligned as necessary?

The idea here is that I want to protect the function from misuse by other users (or me after 6 months). I know how to align the material that I want to convey to him. I would like to guarantee that no one will be able to convey to them the inconsistent things.

Based on this answer , I think the answer to my question is “no”, this cannot be done during the build, but it seems useful, so I decided to check. My job is to put assert((((size_t)ptr) % 4) == 0);in a function, so at least I could capture it at runtime while debugging.

In my experience, the results are undefined if you have inconsistent uint8_t*on uint32_t*many built-in platforms, so I don’t want to rely on the “right” result coming out at the end. Plus it is used in a real-time system, so slowing down may be unacceptable.

Quotes are welcome if available.

+4
source share
2 answers

No, nothing in the C or C ++ standards that I know of can make the pointer parameter hold the corresponding value.

To get memory, use posix_memalign:

#include <stdlib.h>

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

DESCRIPTION

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

After successful completion, the value pointed to by memptr should be a multiple of alignment.

+1
source

For dynamic allocation, take a look at the standard (starting with C11) aligned_alloc.

, . gcc, , aligned.

0

Source: https://habr.com/ru/post/1668013/


All Articles