Compiler bug: Pointer incorrectly assigned

Discussion about Z-Uno product. Visit http://z-uno.z-wave.me for more details.
Post Reply
droll
Posts: 48
Joined: 20 Dec 2013 01:37

Compiler bug: Pointer incorrectly assigned

Post by droll »

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.

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;
}
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.

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;
}

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:

Code: Select all

   ..
   if (c>0x5F)
      c-=32;
   char c2=c;
   const unsigned char *FontPtr=&Font5x8[c2];
   ..
The generated code will use as index the declared but not yet defined variable c2:

Code: Select all

     char c2;
     const unsigned char * FontPtr = &Font5x8[c2];
     unsigned char v;
     if(c > 0x5F)
     {
          c -= 32;
     }
     c2 = c;
     v = *FontPtr++;
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.
User avatar
PoltoS
Posts: 7571
Joined: 26 Jan 2011 19:36

Re: Compiler bug: Pointer incorrectly assigned

Post by PoltoS »

Well, it is always good to define variables at the beginning of the scope/block. We will chekc how does it fit specs and will fix that (easy fix is to place { .. } around the code after the if)
Post Reply