问题
volatile
seems to be a never ending question of every one. I thought I knew everything about it, but then I encountered this:
So, I have a piece of memory shared between threads and I defined it like this:
volatile type *name;
If it makes you feel better, you can imagine type
is just an int
.
This means I have a pointer (that is not volatile) to some data that are volatile. So, for example when it comes to optimizing, the compiler can cache the value of name
but not name[0]
. Am I right?
So, now I am vfree
ing this pointer (it's in a Linux kernel module) and it tells me that vfree
expects const void *
while I am passing it volatile type *
.
I understand how it can be dangerous to pass a volatile type *
as a type *
because in that function, the values of name[i]
could be cached (as a result of optimization) which is not desirable.
I don't understand why though, vfree
expects me to send it a pointer necessarily to non-volatile data. Is there something I am missing there? Or is it just the guys who wrote vfree
not thinking about this situation?
I assume me simply casting my pointer to void *
would not cause any harm, is that right?
回答1:
The vfree
function (and every sane deallocation function in general) does not care about your actual data (be it volatile
or not). It just expects a (valid) pointer (think: passing the pointer as a long
value in a CPU register).
Based on that value, the function will:
- call the SLAB/SLUB to free the memory
- remove the memory mapping
So yes, casting to a void *
will not cause any harm at runtime.
回答2:
My conclusion was that just casting the pointer to void *
would not cause a problem and the fact that free
and vfree
don't directly accept pointers to volatile
data is just something that was overlooked.
来源:https://stackoverflow.com/questions/7808543/freeing-vfree-ing-pointer-to-volatile-data