0

Have a global variable that I do not want anyone, but an ISR function, to change, the variable is g_epoch, so see the code below:

#include <stdint.h>

volatile const uint32_t g_epoch = 0;

void adc_ISR() {
        static uint32_t epoch = 0;

        ++epoch;

        *(const_cast<uint32_t*>(&g_epoch)) = epoch;  // Expecting g_epoch to change

        printf("g_epoch adr: %x, const_casted adr: %x, epoch: %x, g_epoch: %x\n",
            (uint32_t)(&g_epoch),
            (const_cast<uint32_t*>(&g_epoch))),
            epoch,
            g_epoch);
}

The output is: g_epoch adr: ACF8, const_casted adr: ACF8, epoch: 28, g_epoch: 0, how come the g_epoch remains zero? Above is the sanitized function, but the code does compile with no warnings.

EDIT: Based on the comments, the variable is placed into the ROM area, and therefore cannot be changed, thank you zneak. But it looks like I can make it work by using pragma and forcing the variable into RAM, but I wont, due to answer by Alessandro Pezzato, since the behavior is undefined.

user1135541
  • 1,781
  • 3
  • 19
  • 41
  • 4
    Attempting to modify a const [is undefined behavior](http://stackoverflow.com/q/22656734/1708801) – Shafik Yaghmour May 28 '15 at 15:39
  • 1
    Not sure if this is just the sanitization, nor does it really provide an answer, but your printf is mixing up epoch and g_epoch, so your output could be misleading. – lordjeb May 28 '15 at 15:43
  • 2
    Your compiler probably put the variable in read-only memory. Your program would probably crash if your CPU was able to detect the illegal access. (Also, consider using `%p` to print pointers instead of casting a pointer to a `uint32_t`). – zneak May 28 '15 at 15:43
  • lordjeb, thanks, it was sanitation, I do not have printf on the mcu I am using, I made a mistake making it into familiar output. – user1135541 May 28 '15 at 15:46
  • Hmmm. That's looks like it should work. How about the unsanitized version? The difference may be the key. Also, is the output you stated coming from the sanitized version, or unsanitized? – donjuedo May 28 '15 at 15:48
  • zneak, you are exactly right, my ram range from the cmd file is: `RAM : origin = 0x1C00, length = 0x4800` So yes it is in ROM area. – user1135541 May 28 '15 at 15:57

1 Answers1

1

const_cast is safe only if you're casting a variable that was originally non-const.

Alessandro Pezzato
  • 8,603
  • 5
  • 45
  • 63