int secret_foo(void)
{
int key = get_secret();
/* use the key to do highly privileged stuff */
....
/* Need to clear the value of key on the stack before exit */
key = 0;
/* Any half decent compiler would probably optimize out the statement above */
/* How can I convince it not to do that? */
return result;
}
Run Code Online (Sandbox Code Playgroud)
我需要在执行key之前从堆栈中清除变量的值return(如代码所示).
如果您感到好奇,这是一个实际的客户需求(嵌入式域).
你可以使用volatile(强调我的):
通过volatile限定类型的左值表达式进行的每次访问(读取和写入)都被视为优化目的的可观察副作用,并且严格根据抽象机器的规则进行评估(即,所有写入都在在下一个序列点之前的某个时间).这意味着在单个执行线程内,相对于由易失性访问的序列点分隔的另一个可见副作用,不能优化或重新排序易失性访问.
volatile int key = get_secret();
Run Code Online (Sandbox Code Playgroud)