4 ms·
Really cool post! Can anyone explain why const makes the array executable? That was the most surprising but for me
by turtletontine 5y ago
Really cool post!
Can anyone explain why const makes the array executable? That was the most surprising but for me
- dj_mc_merlin 5y agoThe real effect he's trying to cause is to move the bytes for main from a R/W memory segment (like .data) to an eXecutable one (like .text). The const keyword tells C that a certain variable should never be modified by code. Doing so would be undefined behaviour. GCC is free to implement whatever guarantees for memory meant for const variables. On some versions and under certain criteria, it would place const variables into .text so any access would cause a SIGSEGV. It can also achieve the same by putting it into other write protected memory, like .rodata (which is what the newest version of gcc prefers for the code in this article, making it no longer work). Why GCC chooses one over the other and why it would change over time are hard questions. A more effective way would be to use __attribute__s (on gcc) or #pragma directives to specify that the bytes need to be in the .text segment. However, that ruins the magic a bit.