SlideShare a Scribd company logo
1 of 1
Download to read offline
The Joy of Programming  |                                      Guest Column 


                                                                                                                  S.G. Ganesh



About the Java Overflow Bug
In this column, we’ll discuss a common overflow bug in JDK, which surprisingly occurs in the widely
used algorithms like binary search and mergesort in C-based languages.



H
          ow does one calculate the average of two integers,                   (they are pointers, they can never be negative). This is also a
          say i and j? Trivial you would say: it is (i + j) / 2.               solution for the overflow problem we discussed on Java.
          Mathematically, that’s correct, but it can overflow                       Is there any other way to fix the problem? If ‘low’ and
when i and j are either very large or very small when using                    ‘high’ are converted to unsigned values and then divided by
fixed-width integers in C-based languages (like Java).                         2, it will not overflow, as in:
Many other languages like Lisp and Python do not have
this problem. Avoiding overflow when using fixed-width                         int mid = ( (unsigned int) low + (unsigned int) high) / 2;
integers is important, and many subtle bugs occur because
of this problem.                                                                   But Java does not support unsigned numbers. Still,
     In his popular blog post [1], Joshua Bloch (Java expert and               Java has an unsigned right shift operator (>>>)—it fills the
author of books on Java intricacies) writes about how a bug                    right-most shifted bits with 0 (positive values remain as
[2] in binarySearch and mergeSort algorithms was found in                      positive numbers; also known as ‘value preserving’). For
his code in java.util.Arrays class in JDK. It read as follows:                 the Java right shift operator >>, the sign of the filled bit is
                                                                               the value of the sign bit (negative values remain negative
1: public static int binarySearch(int[] a, int key) {                          and positive values remain positive; also known as ‘sign-
2:           int low = 0;                                                      preserving’). Just as an aside for C/C++ programmers:
3:           int high = a.length - 1;                                          C/C++ has only the >> operator and it can be sign or value
4:                                                                             preserving, depending on implementation. So we can use
5:           while (low <= high) {                                             the >>> operator in Java:
6:                          int mid = (low + high) / 2;
7:                          int midVal = a[mid];                               int mid = (low + high) >>> 1;
8:
9:                          if (midVal < key)                                      The result of (low + high), when treated as unsigned
10:                                     low = mid + 1                          values and right-shifted by 1, does not overflow!
11:                         else if (midVal > key)                                 Interestingly, there is another nice ‘trick’ to finding the
12:                                     high = mid - 1;                        average of two numbers: (i & j) + (i ^ j) /2. This expression
13:                         else                                               looks strange, doesn’t it? How do we get this expression?
14:                                     return mid; // key found               Hint: It is based on a well-known Boolean equality, for
15:          }                                                                 example, as noted in [4]: “(A AND B) + (A OR B) = A + B =
16:          return -(low + 1); // key not found.                              (A XOR B) + 2 (A AND B)”.
17: }                                                                              A related question: How do you detect overflow when
                                                                               adding two ints? It’s a very interesting topic and is the
    The bug is in line 6—”int mid = (low + high) / 2;”. For                    subject for next month’s column.
large values of ‘low’ and ‘high’, the expression overflows
and becomes a negative number (since ‘low’ and ‘high’                             References:
represent array indexes, they cannot be negative).                                • googleresearch.blogspot.com/2006/06/extra-extra-read-all-
                                                                                    about-it-nearly.html
    However, this bug is not really new—rather, it is usually                     • bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045582
not noticed. For example, the classic K & R book [3] on                           • The C Programming Language, Brian W. Kernighan, Dennis
C has the same code (pg 52). For pointers, the expression                           M. Ritchie, Prentice-Hall, 1988.
(low + mid) / 2 is wrong and will result in compiler error,                       • home.pipeline.com/~hbaker1/hakmem/boolean.html#item23
since it is not possible to add two pointers. So, the book’s
solution is to use subtraction (pg 113):                                          About the author:
                                                                                 S G Ganesh is a research engineer in Siemens (Corporate
mid = low + (high-low) / 2
                                                                                 Technology). His latest book is “60 Tips on Object Oriented
                                                                                 Programming”, published by Tata McGraw-Hill in December
                                                                                 2007. You can reach him at sgganesh@gmail.com.
        This finds ‘mid’ when ‘high’ and ‘low’ are of the same sign

12  |  February 2009 | LINuX For you | www.openITis.com

More Related Content

What's hot

What's hot (9)

1 puc programming using c++
1 puc programming using c++1 puc programming using c++
1 puc programming using c++
 
4. SQL in DBMS
4. SQL in DBMS4. SQL in DBMS
4. SQL in DBMS
 
Literals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersLiterals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiers
 
Elgamal digital signature
Elgamal digital signatureElgamal digital signature
Elgamal digital signature
 
Dbms ER Model
Dbms ER ModelDbms ER Model
Dbms ER Model
 
Learn Java Part 2
Learn Java Part 2Learn Java Part 2
Learn Java Part 2
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Hello world! Intro to C++
Hello world! Intro to C++Hello world! Intro to C++
Hello world! Intro to C++
 
Relation Algebra
Relation AlgebraRelation Algebra
Relation Algebra
 

Viewers also liked (7)

Regional Overview: Youth in Asia and the Pacific
Regional Overview: Youth in Asia and the PacificRegional Overview: Youth in Asia and the Pacific
Regional Overview: Youth in Asia and the Pacific
 
Pyjama
PyjamaPyjama
Pyjama
 
Saint patrick's day
Saint patrick's daySaint patrick's day
Saint patrick's day
 
Merry Christmas History and Celebrations
Merry Christmas History and CelebrationsMerry Christmas History and Celebrations
Merry Christmas History and Celebrations
 
Goretty
GorettyGoretty
Goretty
 
Youth Flash, June 2012
Youth Flash, June 2012Youth Flash, June 2012
Youth Flash, June 2012
 
Faça Acontecer: Desenvolva Seu Comportamento Empreendedor
Faça Acontecer: Desenvolva Seu Comportamento EmpreendedorFaça Acontecer: Desenvolva Seu Comportamento Empreendedor
Faça Acontecer: Desenvolva Seu Comportamento Empreendedor
 

Similar to 26 Jo P Feb 09

24 common mistakes in go (gotchas) and how to avoid them
24 common mistakes in go (gotchas) and how to avoid them24 common mistakes in go (gotchas) and how to avoid them
24 common mistakes in go (gotchas) and how to avoid themKaty Slemon
 
DEFUN 2008 - Real World Haskell
DEFUN 2008 - Real World HaskellDEFUN 2008 - Real World Haskell
DEFUN 2008 - Real World HaskellBryan O'Sullivan
 
DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019Sabrina Marechal
 
Labsheet2 stud
Labsheet2 studLabsheet2 stud
Labsheet2 studrohassanie
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As CompDavid Halliday
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As CompDavid Halliday
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingLex Sheehan
 
JavaScript: Core Part
JavaScript: Core PartJavaScript: Core Part
JavaScript: Core Part維佋 唐
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2Tekendra Nath Yogi
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators pptViraj Shah
 

Similar to 26 Jo P Feb 09 (20)

24 common mistakes in go (gotchas) and how to avoid them
24 common mistakes in go (gotchas) and how to avoid them24 common mistakes in go (gotchas) and how to avoid them
24 common mistakes in go (gotchas) and how to avoid them
 
13 Jo P Jan 08
13 Jo P Jan 0813 Jo P Jan 08
13 Jo P Jan 08
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
 
14 Jo P Feb 08
14 Jo P Feb 0814 Jo P Feb 08
14 Jo P Feb 08
 
Labsheet2
Labsheet2Labsheet2
Labsheet2
 
DEFUN 2008 - Real World Haskell
DEFUN 2008 - Real World HaskellDEFUN 2008 - Real World Haskell
DEFUN 2008 - Real World Haskell
 
DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019
 
17 Jo P May 08
17 Jo P May 0817 Jo P May 08
17 Jo P May 08
 
22 Jop Oct 08
22 Jop Oct 0822 Jop Oct 08
22 Jop Oct 08
 
Class 8 Lecture Notes
Class 8 Lecture NotesClass 8 Lecture Notes
Class 8 Lecture Notes
 
Labsheet2 stud
Labsheet2 studLabsheet2 stud
Labsheet2 stud
 
Cpp Homework Help
Cpp Homework Help Cpp Homework Help
Cpp Homework Help
 
C Programming
C ProgrammingC Programming
C Programming
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As Comp
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As Comp
 
Code generation
Code generationCode generation
Code generation
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
 
JavaScript: Core Part
JavaScript: Core PartJavaScript: Core Part
JavaScript: Core Part
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators ppt
 

More from Ganesh Samarthyam

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeGanesh Samarthyam
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGanesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationGanesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterGanesh Samarthyam
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Ganesh Samarthyam
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckGanesh Samarthyam
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageGanesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Ganesh Samarthyam
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz QuestionsGanesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz QuestionsGanesh Samarthyam
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizGanesh Samarthyam
 

More from Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 

Recently uploaded

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 

Recently uploaded (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

26 Jo P Feb 09

  • 1. The Joy of Programming  | Guest Column  S.G. Ganesh About the Java Overflow Bug In this column, we’ll discuss a common overflow bug in JDK, which surprisingly occurs in the widely used algorithms like binary search and mergesort in C-based languages. H ow does one calculate the average of two integers, (they are pointers, they can never be negative). This is also a say i and j? Trivial you would say: it is (i + j) / 2. solution for the overflow problem we discussed on Java. Mathematically, that’s correct, but it can overflow Is there any other way to fix the problem? If ‘low’ and when i and j are either very large or very small when using ‘high’ are converted to unsigned values and then divided by fixed-width integers in C-based languages (like Java). 2, it will not overflow, as in: Many other languages like Lisp and Python do not have this problem. Avoiding overflow when using fixed-width int mid = ( (unsigned int) low + (unsigned int) high) / 2; integers is important, and many subtle bugs occur because of this problem. But Java does not support unsigned numbers. Still, In his popular blog post [1], Joshua Bloch (Java expert and Java has an unsigned right shift operator (>>>)—it fills the author of books on Java intricacies) writes about how a bug right-most shifted bits with 0 (positive values remain as [2] in binarySearch and mergeSort algorithms was found in positive numbers; also known as ‘value preserving’). For his code in java.util.Arrays class in JDK. It read as follows: the Java right shift operator >>, the sign of the filled bit is the value of the sign bit (negative values remain negative 1: public static int binarySearch(int[] a, int key) { and positive values remain positive; also known as ‘sign- 2: int low = 0; preserving’). Just as an aside for C/C++ programmers: 3: int high = a.length - 1; C/C++ has only the >> operator and it can be sign or value 4: preserving, depending on implementation. So we can use 5: while (low <= high) { the >>> operator in Java: 6: int mid = (low + high) / 2; 7: int midVal = a[mid]; int mid = (low + high) >>> 1; 8: 9: if (midVal < key) The result of (low + high), when treated as unsigned 10: low = mid + 1 values and right-shifted by 1, does not overflow! 11: else if (midVal > key) Interestingly, there is another nice ‘trick’ to finding the 12: high = mid - 1; average of two numbers: (i & j) + (i ^ j) /2. This expression 13: else looks strange, doesn’t it? How do we get this expression? 14: return mid; // key found Hint: It is based on a well-known Boolean equality, for 15: } example, as noted in [4]: “(A AND B) + (A OR B) = A + B = 16: return -(low + 1); // key not found. (A XOR B) + 2 (A AND B)”. 17: } A related question: How do you detect overflow when adding two ints? It’s a very interesting topic and is the The bug is in line 6—”int mid = (low + high) / 2;”. For subject for next month’s column. large values of ‘low’ and ‘high’, the expression overflows and becomes a negative number (since ‘low’ and ‘high’ References: represent array indexes, they cannot be negative). • googleresearch.blogspot.com/2006/06/extra-extra-read-all- about-it-nearly.html However, this bug is not really new—rather, it is usually • bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045582 not noticed. For example, the classic K & R book [3] on • The C Programming Language, Brian W. Kernighan, Dennis C has the same code (pg 52). For pointers, the expression M. Ritchie, Prentice-Hall, 1988. (low + mid) / 2 is wrong and will result in compiler error, • home.pipeline.com/~hbaker1/hakmem/boolean.html#item23 since it is not possible to add two pointers. So, the book’s solution is to use subtraction (pg 113): About the author: S G Ganesh is a research engineer in Siemens (Corporate mid = low + (high-low) / 2 Technology). His latest book is “60 Tips on Object Oriented Programming”, published by Tata McGraw-Hill in December 2007. You can reach him at sgganesh@gmail.com. This finds ‘mid’ when ‘high’ and ‘low’ are of the same sign 12  |  February 2009 | LINuX For you | www.openITis.com