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?
Yes, the standard quote you've posted covers precisely what you're trying to do. By doing the cast, you're pretending the objects in the array are unsigned char
when they're actually volatile unsigned char
, so inside the function, you're referring to volatile
object through an lvalue without a volatile
qualifier. Undefined Behaviour.
If you cannot change the function storeArray
, you will have to copy the data from the volatile array to a non-volatile one before passing it to the function.
Regarding the second question: the pointer arithmetic is fine, it will simply convert buffer
to an unsigned char*
and then add 3 to the resulting pointer, pointing to buffer[3]
(but with the wrong qualification).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With