[問題] volatile的正確用法
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
VC++/GCC/CLANG
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
None
問題(Question):
volatile大概是C/C++最難了解的關鍵字之一
最近在看完這篇[How to zero a buffer](http://bit.ly/1wmpbys)產生的問題
在開啟最佳化之後,對照Assembly Code,所有的編譯器會捨棄掉stack上的memset。
不過如果照他的方式刻一個,會發現所有Compiler都會做清空的動作
static void
secure_memzero(void * p, size_t len)
{
volatile uint8_t * _p = p;
while (len--) *_p++ = 0;
}
不過中間有句話不太明瞭
The C standard states that accesses to volatile objects are part of the
unalterable observable behaviour — but it says nothing about accesses via
lvalue expressions with volatile types. Consequently a sufficiently
intelligent compiler can still optimize the buffer-zeroing away in this case
— it just has to prove that the object being accessed was not originally
defined as being volatile.
我不知道這段話是否正確,不過還沒找到Standard是否有類似的規定
如果這段話是正確的話,目前找到的
C11的[memset_s](http://bit.ly/1qJG7vv)
Windows的[SecureZeroMemory](http://bit.ly/1oC33rV)
作法都一樣,難道不怕被最佳化掉嘛
請大家指點迷津吧..
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.115.47.165
※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1410531700.A.6AF.html
→
09/13 03:05, , 1F
09/13 03:05, 1F
→
09/13 03:15, , 2F
09/13 03:15, 2F
→
09/13 03:21, , 3F
09/13 03:21, 3F
→
09/13 03:23, , 4F
09/13 03:23, 4F
→
09/13 07:29, , 5F
09/13 07:29, 5F
→
09/13 07:29, , 6F
09/13 07:29, 6F
推
09/14 01:19, , 7F
09/14 01:19, 7F
→
09/14 04:29, , 8F
09/14 04:29, 8F
→
09/14 09:00, , 9F
09/14 09:00, 9F
→
09/14 09:01, , 10F
09/14 09:01, 10F
討論串 (同標題文章)