I have a global volatile unsigned char array volatile unsigned char buffer[10]
to which data is written in an interupt. I have a function that takes an unsigned char * and stores that value to hardware (EEPROM) void storeArray(unsigned char *array)
, in this example the first three values. Is it safe to cast the volatile array to a non-volatile array like so?
store_array((unsigned char *) buffer);
I read the following, which I do not quite understand, but which concerns me:
6.7.3:5 If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.
Does this affect my code?
Then I have this followup question: The buffer array only has a section of data I want to store (can't change that), for this example beginning with the third value. Is it legit to do the following?
store_array((unsigned char *) buffer + 3);
If it is, how is the cast affected, if 3
is added to the array? BR and thank you!
EDIT: @Cacahuete Frito linked a very similar question: Is `memcpy((void *)dest, src, n)` with a `volatile` array safe?
volatile
does what you want on your platform, then it's okay for you to use it. You're relying on non-portable aspects ofvolatile
anyway, and ... in for a penny, in for a pound. If your compiler's treatment ofvolatile
changes, your code can break anyway. So what do you have to lose? – EphemeralstoreArray((unsigned char *) buffer + 3);
: How does the function know where the array ends? If it has the size hardcoded, the pointer arithmetics may force the function to read 3 bytes beyond the buffer limits, and therefore UB. – Madocvolatile
is the same, but the keywords are a little different; we'll see what others think. And sorry, I didn't read that of the 3 elements :) – Madocvolatile
see also electronics.stackexchange.com/q/409545/6383 – Benzene