-
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
fix: add bounds check to prevent out-of-range access in sparse table #2963
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
base: master
Are you sure you want to change the base?
Conversation
int p = logs[end - beg + 1]; | ||
int pLen = 1 << p; | ||
if (p >= (int)table.size() || beg >= (int)table[p].size() || (end - pLen + 1) >= (int)table[p].size()) { | ||
std::cerr << "Error: index out of bounds when accessing sparse table." << std::endl; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
throw an error instead
@@ -83,10 +83,19 @@ std::vector<std::vector<T> > buildTable(const std::vector<T>& A, | |||
template <typename T> | |||
int getMinimum(int beg, int end, const std::vector<T>& logs, | |||
const std::vector<std::vector<T> >& table) { | |||
if(beg<0||end<<beg||end>=(int)table[0].size()){ | |||
cout<<"Error:querry range ["<<beg<<","<<end<<"] is invalid."<<endl; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
cout<<"Error:querry range ["<<beg<<","<<end<<"] is invalid."<<endl; | |
throw std::invalid_argument("Error:query range ["<<beg<<","<<end<<"] is invalid."); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we can also force beg > 0 by using unsigned integer instead preferably uint32_t
@@ -83,10 +83,19 @@ std::vector<std::vector<T> > buildTable(const std::vector<T>& A, | |||
template <typename T> | |||
int getMinimum(int beg, int end, const std::vector<T>& logs, | |||
const std::vector<std::vector<T> >& table) { | |||
if(beg<0||end<<beg||end>=(int)table[0].size()){ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
also why are we left shifting end by beg?
shouldnt it be
if(beg<0||end<<beg||end>=(int)table[0].size()){ | |
if(beg < 0 || end < beg || end >= (int) table[0].size()){ |
Description of Change
Fix the out-of-bounds access in `getMinimum()` function in `sparse_table_range_queries.cpp`.Added a boundary check to ensure stable behavior for invalid range queries.
Checklist
Notes:
This fix prevents crashes due to out-of-bounds access in RMQ function.