Arduino icon indicating copy to clipboard operation
Arduino copied to clipboard

Bug in a array

Open MasterCynder opened this issue 11 years ago • 3 comments

Hello, i've find a bug in the 1.6.0 and 1.6.1 (but not present in the 1.0.5 and 1.0.6 (for the other, i don't know)) In this function I use :

int readMinutes () 
{ 
   char stTemp[2]; 
   char key; 
   char minute[2]; 
   int minutes; 
   for (int i=0; i<2; ++i) 
   {
      do 
      { 
         key = keypad.waitForKey(); 
         if (key != NO_KEY) 
            buttonBip(100); 
         if (key == '*') 
            return -1; 
         sprintf(stTemp,"%c",key);
      } 
      while (key == NO_KEY || key == '*' || key == '#' || ((atoi(stTemp)) >= 6 && i == 0)); 
      minute[i] = key; 
      Serial.println(key); 
      lcd.print(key); 
   } 
   minutes = atoi(minute); 
   Serial.print("minutes : "); 
   Serial.println(minute); 
   return minutes; 
}

This function is used to record the key pressed by a keypad in a minutes format "mm". Int the 1.0.5 version of the IDE, the code work correctly, but in the 1.6.1, the array "minute[]" contain 3 char (normally 2 !!!!!) I've verified the "key" variable is used 2 time (for 2 char) so it's must be impossible to have 3 char in the array "minute[]"

MasterCynder avatar Mar 23 '15 13:03 MasterCynder

Could you post your code again with proper indentation and newlines? Also use the ``` (fenced code blocks) markup to make it a properly formatted code block. We really can't properly read it now.

matthijskooijman avatar Mar 23 '15 14:03 matthijskooijman

like this ?

MasterCynder avatar Mar 23 '15 14:03 MasterCynder

Looking at your code, the problem is that, as you say, the minute array has 2 elements, but you didn't make sure that there is any nul-termination. If you pass the array to atoi, or Serial.println, it will print characters until it comes across a NUL. Since both elements of the array are non-NUL, it will just continue reading whatever memory is after minute (which is probably the minutes variable).

If this worked in 1.0.6, that was just lucky, probably because somehow the minutes variable was initialized to 0 (or it ended up in place in memory that was just accidentally always 0). I don't believe this is a bug in Arduino, but a problem in your code.

For future reference, this tracker is not intended for debugging help, just for reporting bugs in the Arduino code itself. Questions like these are better posted on the Arduino forums (if you're not sure if it's a bug in Arduino or your code, asking on the forums is also recommended). Thanks!

matthijskooijman avatar Mar 23 '15 14:03 matthijskooijman