Skip to content

Fix undefined behaviour in unpack() #10943

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed

Conversation

nielsdos
Copy link
Member

atoi()'s return value is actually undefined when an underflow or overflow occurs. For example on 32-bit on my system the overflow test which inputs "h2147483648" results in repetitions==2147483647 and on 64-bit this gives repetitions==-2147483648. The reason the test works on 32-bit is because there's a second undefined behaviour problem: in case 'h' when repetitions==2147483647, we add 1 and divide by 2. This is signed-wrap undefined behaviour and accidentally triggers the overflow check like we wanted to.

Avoid all this trouble and use strtol with explicit error checking.

This also fixes a semantic bug where repetitions==INT_MAX would result in the overflow check to trigger, even though there is no overflow.

atoi()'s return value is actually undefined when an underflow or
overflow occurs. For example on 32-bit on my system the overflow test
which inputs "h2147483648" results in repetitions==2147483647 and on
64-bit this gives repetitions==-2147483648. The reason the test works on
32-bit is because there's a second undefined behaviour problem:
in case 'h' when repetitions==2147483647, we add 1 and divide by 2.
This is signed-wrap undefined behaviour and accidentally triggers the
overflow check like we wanted to.

Avoid all this trouble and use strtol with explicit error checking.

This also fixes a semantic bug where repetitions==INT_MAX would result
in the overflow check to trigger, even though there is no overflow.
@nielsdos nielsdos changed the title Fix undefined behaviour in pack() Fix undefined behaviour in unpack() Mar 28, 2023
@nielsdos nielsdos closed this in 8786283 Mar 28, 2023
@nielsdos
Copy link
Member Author

This was for unpack(), but looks like the pack() function has the same problem. I'll try to look at it this week sometime.

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

Successfully merging this pull request may close these issues.

2 participants