Products > Programming

memcpy() and volatile

(1/34) > >>

Simon:
My program is totally failing to work in parts and I suspect it is due to some variables being optimized out or in fact some code just being ignored. While the variables can be observed to have values in some places they do not.

Yes they are altered in interrupt routines. If I make the variables volatile every use of memcpy() throws a warning. What do I do?

langwadt:
if they are changed in interrupt they have to be volatile, so don't use memcpy

https://stackoverflow.com/a/36729638

Simon:
unfortunately as I am extracting data from CAN bus stream and putting in into the variable of the. type that it is I have little choice but to use memcpy().

The whole point of using volatile is not really for many of the reasons it is used but simply to make the damn compiler do as it is told. I want this calculation doing so do it and don't assume that value is 0 because you decided.

Jeroen3:
No the compiler doesn't try to know better then you. You just didn't tell him everything.  ;)

The compiler can only see what happens in the main thread. So, all functions called from main().
If it then tries to follow the logic and never sees any change to the `int number = 0` you've put there, it will think it's 0. No point in keeping in memory then.
If anything else changes `int number`, such as an interrupt handler, other thread or hardware. You must tell the compiler to assume this value is different every read. And for good measure, ensure it is written every write. In the exact order you wrote. With the volatile keyword.

CAN registers will be marked volatile by the vendor header file. You cannot use memcpy on hardware registers because,
- memcpy cannot guarantee data access width and alignment. (void*!)
- memcpy cannot guarantee data access order. (this can be implementation specific)
- memcpy cannot guarantee atomicity of the read. (data could change during copy)
(it may not even be threadsafe?)
Thus memcpy takes `void*`, which should be fine to copy within standard application memory.

That the compiler throws you a discard volatile warning is your lucky day saving you from way more possible bugs.
memcpy is not the function for your are looking for.

Simon:
I also get warnings where I use pointers, again unavoidable.

Navigation

[0] Message Index

[#] Next page

There was an error while thanking
Thanking...
Go to full version
Powered by SMFPacks Advanced Attachments Uploader Mod