Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is It Safe to Cast Away volatile?

Tags:

c++

Most of the time, I am doing this way.

class a {
public:
    ~ a() {
        i = 100;          // OK
        delete (int *)j;  // Compiler happy. But, is it safe?
                          // The following code will lead compilation error : delete j;
    }

private:
    volatile int i;
    volatile int *j;
};

int main() {
    a aa;

}

However, I saw an article here:

https://www.securecoding.cert.org/confluence/display/seccode/EXP32-C.+Do+not+access+a+volatile+object+through+a+non-volatile+reference

Casting away volatile allows access to an object through a non-volatile reference. This can result in undefined and perhaps unintended program behavior.

So, what will be the workaround for my above code example?

Here is the error message I get if I use

delete j

Note that, this is output from VC6 (Don't ask why I am using VC6!)

c:\projects\a\a.cpp(5) : error C2664: 'delete' : cannot convert parameter 1 from 'volatile int *' to 'void *' Conversion loses qualifiers

like image 507
Cheok Yan Cheng Avatar asked Mar 19 '10 03:03

Cheok Yan Cheng


2 Answers

Nothing. If you don't access the volatile memory, the semantics of volatile are unaffected. If you accessed volatile memory through a casted non-volatile pointer, the compiler might optimize the reference away. If the value had changed, you'd have the wrong value. For some value of wrong. ;-)

The delete doesn't access the volatile memory, it just frees it. Sort of an uncommon thing to do with volatile memory.

like image 183
Richard Pennington Avatar answered Oct 28 '22 09:10

Richard Pennington


deleteing a volatile would imply that you've serialized access to it so it is not, in fact, volatile any more. The proper way to remove the volatile (once you know it's safe) is with const_cast<int*>.

If the pointer, and not the int, is volatile, then you really meant int *volatile j. Moreover, if all the members of a class are volatile, you probably want to qualify the entire object at once, a volatile aa;.

like image 22
Potatoswatter Avatar answered Oct 28 '22 09:10

Potatoswatter