Compiler bug: Pointer incorrectly assigned
Posted: 07 Jan 2017 20:00
I found a really weird problem with the C compiler that is used for Z-Uno (version 2.0.7)! Let's have a look at the function below. It contains the pointer variable FontPtr that points to the element of the array Font5x8 defined by the argument 'c'. Important to note is that the argument can be modified before it is used as index.
This code is pre-processed by the C compiler in 2 steps. After the second step the generated code becomes incorrect (file: SharpMemoryLCD_ucxx.c). The pointer assignment is made on the very beginning of the function and the fact that the index variable 'c' can be modified is fully ignored.
Interesting is that the other non-pointer variable 'c2' is handled correctly.
Let's check what is happening if as index the variable 'c2' is used instead of 'c'. So the original code is:
The generated code will use as index the declared but not yet defined variable c2:
And the moral of this story is: Don't declare and assign pointers in a single statement. Use separate statements for a pointer declaration and assignment.
Code: Select all
char MyFunction(char c) {
if (c>0x5F)
c-=32;
char c2=c;
const unsigned char *FontPtr=&Font5x8[c];
unsigned char v=*FontPtr++;
return c2*v;
}
Code: Select all
char MyFunction(char c)
{
char c2;
const unsigned char * FontPtr = &Font5x8[c];
unsigned char v;
if(c > 0x5F)
{
c -= 32;
}
c2 = c;
v = *FontPtr++;
return c2 * v;
}
Let's check what is happening if as index the variable 'c2' is used instead of 'c'. So the original code is:
Code: Select all
..
if (c>0x5F)
c-=32;
char c2=c;
const unsigned char *FontPtr=&Font5x8[c2];
..
Code: Select all
char c2;
const unsigned char * FontPtr = &Font5x8[c2];
unsigned char v;
if(c > 0x5F)
{
c -= 32;
}
c2 = c;
v = *FontPtr++;