Skip to content

Fix regidx out-of-bounds array access and double free#2533

Merged
pd3 merged 1 commit intosamtools:developfrom
sirus20x6:fix/regidx-oob
Mar 31, 2026
Merged

Fix regidx out-of-bounds array access and double free#2533
pd3 merged 1 commit intosamtools:developfrom
sirus20x6:fix/regidx-oob

Conversation

@sirus20x6
Copy link
Copy Markdown
Contributor

Summary

  • Cap iend to list->nidx - 1 instead of list->nidx in regidx_overlap — the loop for (i=ibeg; i<=iend; i++) could read list->idx[nidx], one past the allocated array
  • Set str.s = NULL after free(str.s) in regidx_init — prevents double free if hts_close() fails and the error path frees str.s again

Test plan

  • Existing test suite passes (1920/1920)
  • Verify region overlap queries at chromosome boundaries

1. regidx_overlap: cap iend to nidx-1 instead of nidx, preventing
   an out-of-bounds read of list->idx[nidx] in the i<=iend loop.

2. regidx_init: set str.s = NULL after freeing it so the error
   path does not double-free when hts_close() fails.
@pd3 pd3 merged commit a49df0c into samtools:develop Mar 31, 2026
0 of 6 checks passed
@pd3
Copy link
Copy Markdown
Member

pd3 commented Mar 31, 2026

Thank you

Comment thread regidx.c
{
int iend = iBIN(end);
if ( iend > list->nidx ) iend = list->nidx;
if ( iend >= list->nidx ) iend = list->nidx - 1;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@daviesrob If correct, I think this affects also regidx.c code in htslib

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not convinced that this is correct. The item count gets incremented by 1 when allocating list->idx, so it can accommodate looking up iend. I assume that it was written that way because the actual range is likely to end somewhere in the middle of the bin.

Because the array is big enough, there is no out of bounds access.

pd3 added a commit that referenced this pull request Apr 2, 2026
As explained by #2533 (comment)
the original code was correct
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.

3 participants