Skip to content

Avoid UB in debug code - #50

Merged
nigels-com merged 2 commits into
boostorg:developfrom
Flamefire:patch-1
Nov 29, 2026
Merged

nigels-com merged 2 commits into
boostorg:developfrom
Flamefire:patch-1

Conversation

@Flamefire

Copy link
Copy Markdown
Contributor

std::memset calls with a nullptr argument are flagged as UB by GCC -fsanitize=undefined, so check the size first

See https://godbolt.org/z/Kjch8dd1d for a simple example showing the diagnostics

Fixes #39

@nigels-com

Copy link
Copy Markdown
Collaborator

There was a similar fix merged this year: 5d8bebb7614157768d49372618ebbe3049375820

My initial thought is that there always ought to be a nullptr check, going by the wording for C memset:

The behavior is undefined if dest is a null pointer.

@nigels-com

Copy link
Copy Markdown
Collaborator

See also: PR #11

@nigels-com

Copy link
Copy Markdown
Collaborator

Claude here had more to say about it.


Bug: debug mode calls memset with a null pointer

Component boost/circular_buffer/debug.hpp: cb_details::do_fill_uninitialized_memory(); called from base.hpp: allocate()
Severity Low: undefined behaviour by the letter of the standard, harmless on mainstream implementations. Breaks UBSan runs.
Affects Debug mode only (BOOST_CB_ENABLE_DEBUG=1). Present since the debug fill was introduced (fc1d341, 2013). Reproduced on develop at 5d8bebb and on the C++11 working tree.
Status Open

Summary

In debug mode, newly allocated storage is filled with 0xcc so that uninitialized elements
are easy to spot. When the requested capacity is 0, allocate() returns a null pointer and
still calls memset(nullptr, 0xcc, 0).

Passing a null pointer to memset is undefined behaviour even when the size is 0.
UndefinedBehaviorSanitizer reports it, so anyone running their tests with
-fsanitize=undefined and BOOST_CB_ENABLE_DEBUG=1 gets a failure from inside the library.
The library's own test suite trips over it.

Reproduction

#define BOOST_CB_ENABLE_DEBUG 1
#include <boost/circular_buffer.hpp>

int main() {
    boost::circular_buffer<int> cb(0);
}
$ g++ -std=c++11 -fsanitize=undefined repro.cpp && ./a.out
include/boost/circular_buffer/debug.hpp:34:16: runtime error: null pointer passed as argument 1, which is declared to never be null

Measured triggers, with debug mode on:

Code UBSan reports
circular_buffer<int> cb; (default constructor, no allocation) 0
circular_buffer<int> cb(0); 1
circular_buffer<int> cb(4); cb.set_capacity(0); 1
circular_buffer_space_optimized<int> cb(10); (starts with internal capacity 0) 1
any of the above with debug mode off 0

The space-optimized buffer hits this routinely, because it often starts with internal
capacity 0, and shrinking can reach 0 again.

Root cause

base.hpp, allocate():

#if BOOST_CB_ENABLE_DEBUG
    pointer p = (n == 0) ? nullptr : alloc().allocate(n);
    cb_details::do_fill_uninitialized_memory(p, sizeof(value_type) * n);   // p may be null, n may be 0
    return p;
#else

debug.hpp:

template <class T>
inline void do_fill_uninitialized_memory(T* data, std::size_t size_in_bytes) noexcept {
#if defined(__GNUC__) && __GNUC__ < 5
    // Avoid warning for calling memset with a constant size of zero
    if( size_in_bytes )
#endif
    std::memset(static_cast<void*>(data), UNINITIALIZED, size_in_bytes);
}

The if (size_in_bytes) guard already exists, but only for GCC older than 5, where it was
added in 5d8bebb to silence a warning. On every other compiler the call goes through with a
null pointer.

Fix

Make the guard unconditional, and test the pointer instead of the size. That covers both
the original GCC 4.x warning and this bug:

template <class T>
inline void do_fill_uninitialized_memory(T* data, std::size_t size_in_bytes) noexcept {
    if (data != nullptr)
        std::memset(static_cast<void*>(data), UNINITIALIZED, size_in_bytes);
}

Alternatively, guard on size_in_bytes != 0, or on both. A null data with a non-zero size
never happens, because allocate() returns null only for n == 0. Testing the pointer
states the actual precondition of memset.

Check that GCC 4.8/4.9 (still in the CI matrix) don't bring back the warning 5d8bebb fixed.
With a run-time check on data they shouldn't, since the size is no longer a constant zero
at the call.

The other overload, do_fill_uninitialized_memory(T&, std::size_t) for fancy pointers, does
nothing, so it is not affected.

Tests to add

  • Run the existing test suite under UBSan in CI with BOOST_CB_ENABLE_DEBUG=1 and without
    -fno-sanitize=nonnull-attribute. Today that would fail in base_test and
    space_optimized_test.
  • No new test code is needed: circular_buffer<int> cb(0) and the space-optimized tests
    already hit this path. It just needs a sanitizer build to observe it.
  • Once fixed, remove -fno-sanitize=nonnull-attribute from any local or CI sanitizer
    commands that were added to work around this.

@Flamefire

Copy link
Copy Markdown
Contributor Author

yes #11 is the exact same fix. Peters recent fix only avoids the compile-time warning, not the UBSan error which is correct as stated by the standard although likely not an issue in practice. On the other hand a sufficiently "smart" compiler may trace the nullptr, determine the code as unreachable and erase the whole program

@nigels-com

Copy link
Copy Markdown
Collaborator

On the other hand a sufficiently "smart" compiler may trace the nullptr, determine the code as unreachable and erase the whole program

Can you clarify that particular point for me?
Why check the size rather than the data pointer?
That seems like the more clear, more obvious criteria, to me, on the face of it.

@Flamefire

Copy link
Copy Markdown
Contributor Author

Can you clarify that particular point for me?

UB gives the compiler the leeway to assume this does not happen and optimize accordingly. A classic example is something like:

void foo(int *myPtr) {
  if(!myPtr) bar(important);
  *myPtr = 42;
  // Code
  if(!myPtr) baz(important_too);
}

Dereferencing a nullptr is UB so the if condition will always be false and hence the condition and call to baz can be removed.
That even works backwards and the compiler will also remove the call to bar. This possibly bubbles up and down. Sometimes called "time travel" optimization

The *myPtr access could be from a function 5 levels deep and the compiler just traced or inlined that.

This could kick in here: You memset a nullptr so that code must be unreachable.
Of course this is theoretical and compilers might exclude the pattern of memset of a nullptr with zero size

Why check the size rather than the data pointer?
That seems like the more clear, more obvious criteria, to me, on the face of it.

IMO only for the UB issue, not the intention. To me this code now reads: "If we have elements, reset them"
With the ptr-check it would be "If we have storage, reset n elements"

@nigels-com

Copy link
Copy Markdown
Collaborator

I do prefer the more simplistic reasoning that std::memset (for historical reasons) should never be called with a nullptr. Can we go with that?

`std::memset` calls with a nullptr argument are flagged as UB by GCC `-fsanitize=undefined`, so check the size first

Fixes boostorg#39
@codecov

codecov Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (develop@5cd52b7). Learn more about missing BASE report.

Additional details and impacted files
@@            Coverage Diff             @@
##             develop      #50   +/-   ##
==========================================
  Coverage           ?   99.43%           
==========================================
  Files              ?       10           
  Lines              ?     4578           
  Branches           ?     3358           
==========================================
  Hits               ?     4552           
  Misses             ?       23           
  Partials           ?        3           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Flamefire

Copy link
Copy Markdown
Contributor Author

I do prefer the more simplistic reasoning that std::memset (for historical reasons) should never be called with a nullptr. Can we go with that?

A nullptr implies zero elements, while the other way may not be true. So we should define the pre-condition of the function and have an assert.
IMO having a non-zero element count means you are required to pass a non-null pointer. Ignoring the memset of n>0 elements if the pointer is null seems odd to me.
If adding an assert it would make the condition be like

    if(data)
        std::memset(static_cast<void*>(data), UNINITIALIZED, size_in_bytes);
    else
        BOOST_CB_ASSERT(size_in_bytes == 0u);

With the else-branch being logically unreachable
In the last commit I added BOOST_CB_ASSERT(data) for comparison.

It's your call as the maintainer, I'm fine either way. Shall I change to the data check?

BTW: checking the call site we could fix it there too. It already has the check which means the check for size_in_bytes would be free:

        pointer p = (n == 0) ? 0 : alloc().allocate(n);
        cb_details::do_fill_uninitialized_memory(p, sizeof(value_type) * n);

@nigels-com
nigels-com merged commit a87bc62 into boostorg:develop Nov 29, 2026
73 of 75 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.

undefined behavior in do_fill_uninitialized_memory()

2 participants