Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Attempting to seed std::linear_congruential_engine<> that has a modulus of 0 results in divide by zero #45718

Copy link
Copy link
Open
@davidgreenaway

Description

@davidgreenaway
Issue body actions
Bugzilla Link 46373
Version unspecified
OS All
CC @mclow

Extended Description

Instantiating a

std::linear_congruential_engine<UIntType, a, c, m>

with a value 0 for "m" indicates that the linear congruential engine should use the full size of the UIntType, instead of explicitly performing a mod operation after each iteration.

While most of the code for std::linear_congruential_engine appears to correctly handle m == 0, attempting to seed the engine from a generator triggers a divide by zero:

#include <random>
#include <stdint.h>

std::random_device device;
std::seed_seq seq{device(), device()};
std::linear_congruential_engine<uint64_t, 6364136223846793005, 1442695040888963407, 0> rng(seq);  // divide by zero

The problem appears to be in the "__seed" function inside the "random" header:

template <class _UIntType, _UIntType __a, _UIntType __c, _UIntType __m>
template<class _Sseq>
void
linear_congruential_engine<_UIntType, __a, __c, __m>::__seed(_Sseq& __q,
                                                 integral_constant<unsigned, 2>)
{
    const unsigned __k = 2;
    uint32_t __ar[__k+3];
    __q.generate(__ar, __ar + __k + 3);
    result_type __s = static_cast<result_type>((__ar[3] +
                                              ((uint64_t)__ar[4] << 32)) % __m);
    __x_ = __c == 0 && __s == 0 ? result_type(1) : __s;
}

where we perform a "... % __m" operation without confirming that __m is non-zero.

I believe this could be resolved by only performing the mod when "__m != 0".

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugzillaIssues migrated from bugzillaIssues migrated from bugzillalibc++libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.random

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.