Page 1 of 1

So interesting program,who can give an explanation?

Posted: Tue Jun 03, 2003 6:44 am
by cxsnew
//main.c
#include <stdio.h>
#include <stdlib.h>

int get_bit(int bitidx,volatile void *addr);

int main()
{
   int i;
   unsigned long test = 0xF0FFFFF3;
   
   i = get_bit(2,&test);
   printf("i=%d\n",i);
   i = get_bit(2,&test);
   printf("i=%d\n",i);
   
   return 0;
}

int get_bit(int bitidx,volatile void *addr)
{
   int bitval;
   
   __asm__ __volatile__(
   "btl %2,%1;
    setc %0;"
   :"=m"(bitval)
   :"m"(*(unsigned long*)addr),"Ir"(bitidx));
   return bitval;
}
Compile and link with: gcc main.c -o mainthen
run this program(main) you will get the following output:
   i = 0 //the correct result as expected
   i = 1075187968
but if you comment the 1st printf,then the output is
   i = 0
You can try this program youself,who can give a reasonable explanation?thanks!

Re:So interesting program,who can give an explanation?

Posted: Tue Jun 03, 2003 7:01 am
by Pype.Clicker
i have
i=1075149568
i=1073831936

are you aware that "setc" only affect *one* byte ? maybe you should better initialize your INT bitval if you don't want weird results.

Knowing this, the reason is obvious : the lowest byte has been wiped as expected (you'll notice those numbers are multiple of 256 :) ), others are garbage.

The first time you call "get_bit", the stack is clean (on your system, not on mine) and thus you have 0 for every other bytes of bitval, but after you called printf, the stack content of get_bit becomes garbage, and you have wrong result.

Be safe : initialize before you use ;)

Also, why enforcing it to be memory ? "=g" (bitval) would be as great.

Re:So interesting program,who can give an explanation?

Posted: Tue Jun 03, 2003 7:14 am
by cxsnew
:D Great!!I never think to check the int bitval,yeah,setc only affect _ONE_ byte!out of my mind of this,too long time waste :(
Now,I know what result in this weird result.Thanks very much!