Prevent view creation with underflowed size#2927
Open
m-ogita wants to merge 1 commit into
Open
Conversation
JohanMabille
left a comment
Member
There was a problem hiding this comment.
Thanks for the fix. No need to perform the computation if stop_val is greater than start_val though.
| { | ||
| size_type n = stop_val - start_val; | ||
| m_size = n / step + (((n < 0) ^ (step > 0)) && (n % step)); | ||
| m_size = std::max(n / step + (((n < 0) ^ (step > 0)) && (n % step)), size_type(0)); |
Member
There was a problem hiding this comment.
Suggested change
| m_size = std::max(n / step + (((n < 0) ^ (step > 0)) && (n % step)), size_type(0)); | |
| m_size = stop_val > start_val ? n / step + (((n < 0) ^ (step > 0)) && (n % step)) : 0u; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Checklist
Description
When a slice with conditions such as
start > stop && step > 0(or vice versa) is used to create a view (sliced or strided), the resulting array view can have an enormous size. Accessing its elements then leads to undefined behavior.Here is a minimal example:
The expected output is
0, but the actual output is18446744073709551613.The cause of this issue appears to be the size calculation in the
xstepped_rangeconstructor inxtensor/include/xtensor/views/xslice.hpp, shown below:When
start_valis greater thanstop_val(or more precisely, whenstop_val - start_valhas the opposite sign fromstep),m_sizecan become negative. This subsequently causes the resulting size to underflow.One simple way to fix this issue is to clamp
m_sizeto a minimum value of0:Note on terminology: > I used the term "underflow" to describe "integer underflow", the behavior where subtracting from a small unsigned integer results in a huge value.