P45 Imminent P45 Imminent - 5 months ago 17
C Question

A type for arbitrary memory in C

This is in reference to this question

How to implement the c malloc/realloc functions properly?

where the accepted answer mentions that a

array can be used to model a pool of arbitrary memory.

However one of the comments to that accepted answer states

A char array that doesn't have allocated storage duration can only be
aliased by a character type. In other words it cannot and it should
not be used as arbitrary memory

Is this correct? If so, then what could be used? I'd like to avoid using
or any specific OS calls - so I'm symmetrical with that question.


I believe the issue he pointed out was that if you allocate a char type array statically and then compile your library with a modern, desktop-like C compiler like gcc, you cannot easily convert the contents of that area to another type. Because then the compiler would perform optimizations based on pointer aliasing and screw everything up, see "the strict aliasing rule".

Simply assure that your compiler does not use strict aliasing and you'll be fine. For example, none of the common embedded systems compilers on the market does this.

With gcc you'd compile as -fno-strict-aliasing. Might be good to always enable warnings for code that would cause such problems -Wstrict-aliasing.

As a side note, uint8_t makes far more sense to use as generic type, because unlike char, it is completely unambiguous: it has no signedness and the size is well-known.