Freeing (vfree-ing) pointer to volatile data

若如初见. 提交于 2019-12-31 04:06:26

问题


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 vfreeing 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:

  1. call the SLAB/SLUB to free the memory
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!