QuantLib icon indicating copy to clipboard operation
QuantLib copied to clipboard

avoid underflow in SmileSectionUtils

Open pcaspers opened this issue 8 months ago • 4 comments

https://github.com/lballabio/QuantLib/blob/50ab670d72c3b64d07c7a8dd7f6a43582604f3f9/ql/termstructures/volatility/smilesectionutils.cpp#L185

rightIndex_ might be zero here, so we should change the code to

                if (rightIndex_ > 0)
                    rightIndex_--;

pcaspers avatar Mar 31 '25 11:03 pcaspers

In that case we should probably skip the calls to erase above that line, right?

I'm not sure though. If rightIndex_ is 0, leftIndex is 0 too. Should that be a special case instead?

lballabio avatar Apr 07 '25 14:04 lballabio

If rightIndex_ == 0 and rightIndex_ < k.size() - 1 we can still erase the point next to the right of rightIndex_, can't we?

Agreed, if rightIndex_ == 0 then leftIndex == 0 because 0 <= leftIndex <= rightIndex_ always. We can separate out this case, if it helps?

My (maybe optimistic) assumption was that the current code is correct with the only exception that L185 only applies if rightIndex_ > 0. I am not sure though.

pcaspers avatar Apr 17 '25 17:04 pcaspers

This issue was automatically marked as stale because it has been open 60 days with no activity. Remove stale label or comment, or this will be closed in two weeks.

github-actions[bot] avatar Jun 17 '25 02:06 github-actions[bot]

I'm working on a fix for this issue and have identified that in addition to the bounds check you mentioned at line 185, there's a similar issue at line 178 where rightIndex_-- also needs protection. Both locations should check if (rightIndex_ > 0) before decrementing to prevent unsigned underflow. While investigating, I also discovered that line 137 has a related issue where the condition order allows af() to be called with out-of-bounds indices. This can be fixed by checking centralIndex < k_.size() - 1 before calling af(centralIndex, centralIndex, centralIndex + 1).

The fix itself is straightforward, but I'd like to include a regression test. However, I haven't been able to craft test data that both triggers the underflow condition and still has a valid arbitrage-free region. The test data I've tried either doesn't exercise the bug or throws a legitimate exception after the fix. I can submit the PR either without a test (since this was identified by code inspection) or with a test if you can provide data that reproduces the condition. Which approach would you prefer?

7astro7 avatar Oct 19 '25 17:10 7astro7