Force the C compiler to read the object's memory
13:27 27 Nov 2025

I duplicated the topic because (possibly) I made a mistake with the section of the site and initially posted in the wrong place: Ways to reliably read an object in C

I have a regular byte buffer declared in file scope:

static unsigned char buffer[32];

At some point, the function to start a DMA read operation into this buffer is called:

void func(void) {
startDMARead(buffer, sizeof(buffer));
...
}

For simplicity, let's assume that startDMARead() is blocking, and when it returns, the data has been physically moved to buffer.

Now I need to manipulate some bytes in the buffer. Can the compiler, without seeing explicit changes to the data in the buffer (write accesses), optimize the subsequent read access by discarding access to the actual 'buffer' object and substituting the fixed (default) value with which this buffer was initialized (specifically, 0)?

I suspect it can, since 'buffer' is declared with the static specifier. A solution would be to mark 'buffer' with the volatile qualifier, but this would create certain difficulties when using this object directly: accesses to it won't be optimized, and values ​​won't be cached in registers. This is a very bad approach.

Another approach is to declare a pointer to a volatile-qulified type at the point of use and access it through it. The correct option in this case would be to access the elements of 'buffer' by its declared type (unsigned char), so as not to violate strict aliasing rules.

For example, I would like to be guaranteed and safe (without violating the fundamental tenets of the C Standard) to read the contents of 'buffer' from the 3rd byte as a 4-byte unsigned int object, allowing the compiler to read the object in any way it sees fit (my CPU supports unaligned data load instructions).

Does calling memcpy(), for example, guarantee the behavior of a real copying, regardless of the compiler's assumptions about the reasonableness of this copying?

c memory memcpy dma