Skip to content

Fix undefined behavior test failures#21

Merged
tjol merged 2 commits intotjol:mainfrom
skeeto:fix-test-undefined-behavior
Mar 6, 2026
Merged

Fix undefined behavior test failures#21
tjol merged 2 commits intotjol:mainfrom
skeeto:fix-test-undefined-behavior

Conversation

@skeeto
Copy link
Copy Markdown
Contributor

@skeeto skeeto commented Feb 12, 2026

The tests currently fail under UBSan:

$ CFLAGS=-fsanitize=undefined LDFLAGS=-fsanitize=undefined cmake -B build
$ cmake --build build
$ build/tests/example_doc_test_v1 2>&1 | grep 'runtime error'
src/tokenizer.c:99:5: runtime error: null pointer passed as argument 2, which is declared to never be null
src/emitter.c:104:20: runtime error: -inf is outside the range of representable values of type 'int'
src/emitter.c:106:9: runtime error: negation of -2147483648 cannot be represented in type 'int'; cast to an unsigned type to negate this value to itself

The specific errors depend on whether you're using GCC or Clang, but that's three instances of undefined behavior. The first comes from passing null to memmove(), which does not accept null pointers (before C2y). My fix tests the length instead of the pointer so that a null pointer with a non-zero length will still trip UBSan rather than hide a bug.

The second is an overflow casting infinity to int, which in practice produces INT_MIN which then overflows abs. I fixed this by not computing the log of zero.

Passing null pointers to memmove() is undefined before C2y, even for a
zero count.
Casting an out-of-range float to an integer is undefined. In practice it
casts to INT_MIN, which then overflowed the abs() in the condition.
@tjol
Copy link
Copy Markdown
Owner

tjol commented Mar 6, 2026

Thanks for this. Sorry I haven't had time for it earlier.

@tjol tjol merged commit d2792e5 into tjol:main Mar 6, 2026
15 checks passed
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.

2 participants