Skip to content

Conversation

@rchateauneu
Copy link

No description provided.

if (i < 0) {
*p++ = '-';
u = -u;
u = (uint32_t)(-(int32_t)u);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unary minus applied to a signed integer is undefined behavior for targets that use two's complement when the value is the most negative value (INT_MIN) representable in two's complement, it causes signed overflow. The compiler can assume this never happens. On clang/llvm this doesn't seem to cause a problem, but on gcc with -O3 optimization the compiler takes advantage of this assumption and generates code that gives the wrong answer (or causes segmentation fault).

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants