Pointers on PIC32 device not matching expected values in the debugger

612 views Asked by At

Quick question here regarding the behavior of pointers (I'm working on a project on a PIC32MX270F256D).

I have the following code currently implemented:

void main(void)
{
    int size = 15;
    int check;
    int *ptr;

    ptr = &size;
    check = *ptr;

    while(1);        //just so it hangs at the end
}

Now I am stepping through the program with variable watches on. After the declaration of size, I can see in the watch window that size has a value 15, and is at address 0xA000FFC8 (so far so good). After the line ptr = &size;, the watch window shows that ptr has value 0xA000FFC8 (as expected). Now after the final line (check = *ptr;), the watch window says check has the value 0xA000FFC8.

This seems to me like very simple functionality. At the end, while hanging in the while loop, check should have the value 15, no? If yes, is my code incorrect, or is there apparently something wrong with the Microchip IDE? If not, what am I missing to make this work like it should?

Thanks.

-Sean

Note: I'm using MPLAB X and the Microchip's XC32 compiler.

1

There are 1 answers

1
indiv On BEST ANSWER

This is probably an optimization issue. Your compiler determined that your code doesn't actually do anything, so it didn't bother generating the code. Specifically, your code doesn't actually use the value you store in check.

You can declare your pointer as volatile to force the compiler not to optimize it away. I.e., int *ptr; becomes volatile int *ptr;.

You could also use the value of check in a meaningful way, like by printing it out.

printf("My pointer %p points to %u.\n", ptr, check);

Or you can look in your compiler documentation and figure out how to turn off optimizations. When debugging, it is often helpful to compile without optimizations so that the compiled code closely matches your source code.

Note: You will at some point want to access hardware or chip registers that have been mapped to memory addresses. When you do this, make sure these pointers to mapped memory are volatile or you will have the same problem!