I find myself wanting to write a routine that will operate on both volatile and non-volatile memory blocks. Something along the lines of:
void byte_swap (unsigned * block_start, size_t amount) {
for (unsigned * lp = block_start; lp < block_start + amount; lp++) {
*lp = htonl(*lp);
}
memcpy (block_start, some_other_address, amount);
}
(Not my real code, but an example).
The problem I have is that if I try to use a pointer to a volatile memory area, the compiler complains about losing the volatile qualifier. I could cast away volatile, but it seems like that might make the routine itself unsafe if it tries to cache the changes (or previous reads), would it not?
The other option would be to make the routine itself take unsigned volatile *
, but that would require me to convert all the non-volatile callers to volatile pointers.
I suppose a third option would be to make two exact duplicates of the routine, differing only in whether the volatile
keyword appears. That sucks.
Is there a Right Way to handle this, and if so what is it?
As a mostly related question, are predefined routines (specifically memcpy) safe to use with volatile pointers? What bad things could happen to me if I did? It seems kinda silly to have to reroll any memory-related library routine myself simply because it doesn't use volatile void pointers.