문제

Is an identifier qualified by const in every case stored as read only? Or will it be determined on run time? And what exactly will and/or could happen when I'm going to write into "Read only" memory.

const char **cpp;
char *p;
const char c = 'A';
cpp = &p;
*cpp = &c;
*p = 0;

Is this code going to modify RO mem in any case? or did this just work because every time I executed it it wasn't RO mem? If so, what will happen if the char is stored in RO mem and I'm executing this code? The behaviour is undefined that's not even a question. But this code is executable. So my question is: What will happen by modifying read only memory?

도움이 되었습니까?

해결책

Basically, it depends on the compiler. Most probably the char will get on stack and will not be readonly (so, const would mean just mess with type conversions, nothing in the executable). The stack is never readonly.

If you define some const as a global, it would most probably get into DATA segment which is not readonly either. So you will again get it all working. Though I can imagine the compiler putting all consts into a special segment with readonly access, in which case you will get a usual access violation/segfault.

Also, you may have a clever compiler that would optimize entire code and replace any occurences of const variable name by its value, and in that case nothing can be told about modifying this variable. Well, most probably the compiler would be clever enough to see &c to understand that the variable must be stored somewhere.

Note the multiple most probably and maybe. Undefined behavior is undefined behavior, so this answer is to be read as we don't know what will happen.

다른 팁

It's undefined behavior, which means you can't know for sure what will happen.

And const variables are not required to be in read only memory.

C11 6.7.3 Type qualifiers

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined. If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.

Firstly, const doesn't guarantee anything about the implementation's use of any read-only memory technology. It simply tells the compiler that the variable is immutable. The compiler can then tell you when you break this invariant. The compiler may do other clever things like optimisations and make use of special storage techniques but that's all implementation specific details.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top