Java Reference
In-Depth Information
if (IsLeapYear(year)) {
if (days > 366) {
days -= 366;
year += 1;
}
} else {
days -= 365;
year += 1;
}
}
}
The original ConvertDays() C function in the real-time clock (RTC) routines for the
MC13783 PMIC RTC takes the number of days since January 1, 1980, and computes the
correct year and number of days since January 1 of the correct year.
The flaw in the code occurs when days has the value 366 because the loop never ter-
minates.Thisbugmanifesteditselfonthe366thdayof2008,whichwasthefirstleapyear
in which this code was active.
Compliant Solution (Zune 30)
This proposed rewrite is provided by “A Lesson on Infinite Loops” by Bryant Zadegan
[Zadegan2009].Theloopisguaranteedtoexit,as days decreasesforeachiterationofthe
loop, unless the while condition fails, in which case the loop terminates.
Click here to view code image
final static int ORIGIN_YEAR = 1980;
/* Number of days since January 1, 1980 */
public void convertDays(long days){
int year = ORIGIN_YEAR;
/* ... */
int daysThisYear = (IsLeapYear(year) ? 366 : 365);
while (days > daysThisYear) {
days -= daysThisYear;
year += 1;
daysThisYear = (IsLeapYear(year) ? 366 : 365);
}
}
This compliant solution is for illustrative purposes and may differ from the solution
implemented by Microsoft.
Search WWH ::




Custom Search