Skip to content

Fix ordertab() segfault when nunique is incorrectly supplied - #207

Merged
MichaelChirico merged 5 commits into
mainfrom
ordertab-segfault
Jan 3, 2026
Merged

Fix ordertab() segfault when nunique is incorrectly supplied#207
MichaelChirico merged 5 commits into
mainfrom
ordertab-segfault

Conversation

@MichaelChirico

Copy link
Copy Markdown
Collaborator

Closes #168. Co-written with Gemini.

The ordertab() C function was susceptible to a buffer overflow when the
'nunique' parameter passed from R was smaller than the actual number of
unique values in the data. This led to intermittent segfaults due to
out-of-bounds writes to the 'ret' array.

This commit introduces a bounds check in the C implementation of
ordertab() (r_ram_integer64_ordertab_asc). If the number of unique
values encountered exceeds the allocated size of the 'ret' vector,
the loop is now terminated early, preventing any out-of-bounds writes
and thus eliminating the segfault. The function will now return a
truncated result in such cases, consistent with R's usual handling
of mismatched lengths.

A new test case has been added to test-sortuse64.R to specifically
target this scenario, using gctorture() to reliably trigger the
condition. This test now passes, confirming the fix.

Updated NEWS.md to reflect this bug fix.
@MichaelChirico
MichaelChirico merged commit e92e1dd into main Jan 3, 2026
10 checks passed
@MichaelChirico
MichaelChirico deleted the ordertab-segfault branch January 3, 2026 07:28
hcirellu pushed a commit to hcirellu/bit64 that referenced this pull request Jan 3, 2026
* Fix: ordertab() segfaults when nunique is smaller than actual

The ordertab() C function was susceptible to a buffer overflow when the
'nunique' parameter passed from R was smaller than the actual number of
unique values in the data. This led to intermittent segfaults due to
out-of-bounds writes to the 'ret' array.

This commit introduces a bounds check in the C implementation of
ordertab() (r_ram_integer64_ordertab_asc). If the number of unique
values encountered exceeds the allocated size of the 'ret' vector,
the loop is now terminated early, preventing any out-of-bounds writes
and thus eliminating the segfault. The function will now return a
truncated result in such cases, consistent with R's usual handling
of mismatched lengths.

A new test case has been added to test-sortuse64.R to specifically
target this scenario, using gctorture() to reliably trigger the
condition. This test now passes, confirming the fix.

Updated NEWS.md to reflect this bug fix.

* To taste

* tighten test

* comment purpose

* citation
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.

ordertab() might segfault

1 participant