Where do the constants stay?

4

Well, as I read the compiler could place them on the stack or in a memory area only read, the standard does not guarantee that it is the first or the second.

According to the standard any attempt to modify a constant type variable is indefinite behavior.

What happens if the compiler decides to place this variable on the stack, does the standard remain firm in this case?

    
asked by cheroky 12.06.2017 в 18:31
source

2 answers

4

Case 1 : The constant ends in a read-only region

Whoever controls that region of memory is read-only is the Operating System ... when detecting a writing attempt it is normal for the OS to kill the application it is trying to write to protect the integrity of the memory.

Case 2 : The constant ends in the stack

The stack is a region of memory that supports read and write operations. In this case the only protection that the value is constant is offered by the compiler and, by the way, it is a very weak protection. Expected in these cases is that the value of the constant can be modified at runtime without problems.

The standard indicates that the result of modifying a constant is indeterminate due to the existence of the first case. Since this behavior depends on the compiler-SO pair it is impossible to give a uniform response.

    
answered by 12.06.2017 / 19:01
source
0

Never lose sight of the fact that C is a portable language; he is expected to compile for various Operating Systems and Architectures, with minimal (or null) changes.

What happens if you compile a code that uses const for an architecture that does not support memory protection? Any micro-controller falls into this category. Or the old MSDOS .

Although it is possible to control this circumstance by using pre-processor macros , the language, itself , has no way of controlling this. It is impossible to control where will end a variable. You can not even be sure that the automatic variables will end up in the stack, because of the simple fact that C does not have the stack concept. em> : you only have the concept of minimum lifetime of a variable. What you think is on the stack, can end anywhere: depends on the architecture . Why else would we have <stdarg.h> ? For this reason, to abstract the concept of step-of-parameters .

It is for all the above that the modification of variables const generates a undefined behavior : an architecture may allow it; Maybe an Operating System does not. A memory access error may be generated. Or maybe demons come out of your nostrils .

    
answered by 12.06.2017 в 20:27