Question

This is my code:

volatile uint32_t value = *((volatile uint32_t *) 0xA0000000); // here `value` is 12498
value *= 2; // here `value` is still 12498
value |= 0x0000001; // still 12498

When analysing the variable value in my debugger, it holds the same value on all lines. What am I doing wrong?

Was it helpful?

Solution

Maybe your debugger isn't actually that good. When one of my tools doesn't seem to behave, I always check it against another tool.

Try to debug the old-fashioned way, with:

volatile uint32_t value = *((volatile uint32_t *) 0xA0000000);
printf ("A:%d\n", value);

value *= 2;
printf ("B:%d\n", value);

value |= 0x0000001;
printf ("C:%d\n", value);

or some other output method if printf is unavailable (it looks like you may be working in the embedded space).

See what you get with that - I'd be more inclined to trust printf-debugging than debuggers.


If your problem is not with value but instead with the memory at location 0xA0000000, then it's working as expected.

You're manipulating the local variable, not the memory location. You need to write the value back, with something like:

*((volatile uint32_t *) 0xA0000000) = value;

However, given your use of volatile, it's entirely possible you just wanted a variable pointer to that location so that changes would reflect immediately.

If that's the case, you would need something along the lines of:

volatile uint32_t *pValue = (volatile uint32_t *) 0xA0000000;
*pValue *= 2;
*pValue |= 0x00000001;

In that case, the memory location would be changed at each instruction without having to explicitly write the value.

OTHER TIPS

  1. It may be that your optimizer has noticed that value is an automatic variable whose address is never taken, and so has in effect ignored the fact that its volatile, since it happens to know something about the architecture it runs on, and has concluded that a conforming program cannot observe what sequence of reads and writes to it occurs even though the standard says this is observable. Obviously that's not very debugger-friendly, but I wouldn't be that surprised if it happens anyway. In effect the compiler would be assuming that you can't "see" the stack, which is false if you use a debugger, examine a core dump, mark the stack read-only and handle the resulting signals, etc. Check the disassembly, see whether the multipy/shift and the bit-set actually appear.
  2. It may be that your debugger isn't tracking the value correctly, either because of (1) or otherwise.

try writing value to another temp variable and examine that value. Sometimes this tricks the compiler/debugger into doing what you want. AFAIK, volatile tells the compiler to always read the value, not necessarily to keep it around for writing if its never read.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top