Skip to content

Possible undefined behavior in new ll2string() implementation. #1940

Closed

Description

@antirez

This is what @CAFxX reported in a commit comment:


if long long svalue == MIN_INT64 then -svalue yields UB (signed overflow - even if it will probably be 0)

#include <stdint.h>

int main() {
  uint64_t X = -INT64_MIN;
  return 0;
} 

Result of compilation:

$ gcc ub.c
ub.c: In function ‘main’:
ub.c:4:16: warning: integer overflow in expression [-Woverflow]
   uint64_t X = -INT64_MIN;

since value in your code is signed, -value is signed as well. If value == INT64_MIN then -value overflows. The C standard says[1] that a signed overflow is UB. AFAICT the fact that by chance the compiler is doing the right thing is irrelevant.

See e.g. http://stackoverflow.com/questions/3679047/integer-overflow-in-c-standards-and-compilers and http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html [1]


I'm currently in vacation but I'll check the issue ASAP. Created a proper issue in order to avoid this to be forget.

Activity

  1. added a commit that references this issue on Aug 15, 2014
  2. antirez commented on Aug 15, 2014

    @antirez
    ContributorAuthor

    @CAFxX and @mattsta, the problem was actually there indeed, thanks, would love to double check with you if the fix I propose seems appropriate.

  3. CAFxX commented on Aug 18, 2014

    @CAFxX

    @antirez from a quick look it looks correct; I will check better ASAP

  4. CAFxX commented on Sep 4, 2014

    @CAFxX

    I finally had time to review it; LGTM.

  5. antirez commented on Sep 4, 2014

    @antirez
    ContributorAuthor

    Thanks @CAFxX, the fix was already shipped with 2.8.14, I also tested it with clang undefined behavior detector just to be sure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions