Incomprensible results from get_states without printf


I have some strange behavior from the code below.

if i remove the printf, i have wrong values inside the variable d.

If someone can give me a clue?
// --- define some value for reed grid ----
#define reed_start_Pin 8
#define reed_end_Pin   23
// colonnes en Pins pairs (start=8) et lignes sur Pins impairs
#define Columns           0x5555 //0b0101010101010101
#define Rows              0xAAAA //0b1010101010101010
#define Dir_RowOut_ColIn  0xAAAA // Output = 1 input = 0

// --- Pin Row Col ----
#define COL_A  reed_start_Pin
#define ROW_1  (reed_start_Pin+1)

// ------ recup les colonnes  ------
// récupere un bit sur 2 en partant de la droite 
// ex  si v = 0b11110010
// retour = 0b1100
int getcolpinval(unsigned int v)
    unsigned int d,i;
    // on passe de 2 en 2 vers la gauche (on shift v vers la droite)
    for (d = 0; v; v >>= 2, i++) {
      // on accumule le résultat dans d
        d = d | (v&1) << i ;
    return d;

// ------ Main Program ------
int main()
  // Mettre les lignes en direction output et les colonnes en input

  // mettre les lignes en High
  unsigned int pinvalues = 0;  // recupere les valeurs des pins
  int rowpin    = 0;  // pins des lignes
  int d = 0;
    term_cmd(CRSRXY, TERM_X0, TERM_Y0);

    for (int r = 4; r>=1; r--){
       // Mettre la ligne a 0 

       // récupère les valeurs des colonnes
       pinvalues = get_states(reed_end_Pin,reed_start_Pin);
      // afficher

       printf ("Row_%d: ",r);                                          ////   <===== here 
       d = getcolpinval(pinvalues);
       printf("\td=%d\n",d);                                         /// <== d is wrong if the printf above is commented
       term_cmd(CRSRXY,TERM_X0,TERM_Y0 + 4-r+1);
       // reinitialiser la ligne a High
      // pause(500);

    } // for row     
  } // for(;;)


  • The only suspect thing I see is the variable i in getcolpinval not initialized (guess it should start from 0).
    Probabily the printf clears the stack locations used by that variable (local variables are allocated on the stack) so it works with printf but not without.
  • laurent974laurent974 Posts: 76
    edited 2020-05-10 - 18:22:10
    Thank you ! It was that. I spend hours reading this code and triturate every pieces. I was about to give up and let the printf.
  • To prevent problems like this, enable compiler warnings!
    (How to do this depends on what compiler/IDE you are using...)
  • i forgot to set it on simpleIde.

    I usually use a makefile with everything inside because when code is too long, vim + makefile are a big win.
    But this time i tried simpleIde and totally forgot to look at the compiler options.
  • If you want to look at the code built by SimpleIDE in the left pane you can right click and there is a show assemble code. You will see in there that variables are allocated in registers and not on the stack.

Sign In or Register to comment.