A Bloom filter answers one question about a set: could this key be in it? It stores no keys, only a bit array. Each inserted key is hashed to a few positions that are set to 1, and a query hashes the key the same way. If all its bits are set, the answer is “probably present”. If any bit is clear, the answer is “definitely not present”. The price is false positives, and the price is predictable: with 100,000 keys, eight bits per key and six hashes gave a measured false-positive rate of 0.021760 against the formula’s 0.021577, and sixteen bits per key gave 0.000470 against 0.000459.
This guide covers the bit array, the k hash functions built by double hashing, the insert and query paths, the false-positive formula and the bits-per-key trade. It then measures the rate against theory for four sizes and eight hash counts, and closes with the uses in databases and caches. The Hash Table article covers exact membership, which is what a Bloom filter gives up. The code was built and tested with GCC 13.3, Clang 18.1.3 and MSVC 19.44, and both languages print byte-identical output.
What Is a Bloom Filter?
A Bloom filter is a probabilistic set-membership structure made of an m-bit array and k hash functions. Inserting a key sets its k bits, and a query checks them: any clear bit proves the key absent, and all bits set means the key is probably present. With n keys inserted, the false-positive rate is about (1 – e^(-kn/m))^k.
Burton Bloom described the structure in 1970, and it became a standard building block because it is tiny and fast. Both insert and query are k hash computations and k bit operations, and no keys are stored. The basic filter cannot delete, because clearing a bit could erase evidence of another key. A query for an inserted key is never wrong, so there are no false negatives, while a query for an absent key can wrongly say “probably present”. That asymmetry is what many systems want: a cheap “definitely not here” that skips an expensive lookup, with a small share of “maybe” answers that go on to the real store.
The formula follows from the bit-setting process. After n inserts, a given bit is still clear with probability (1 – 1/m)^(kn), which is about e^(-kn/m). An absent key’s k bits are therefore all set with probability (1 – e^(-kn/m))^k. The best k for a given m/n is (m/n) ln 2, and the best rate for b bits per key is about 0.6185^b. Eight bits per key gives about 2 percent and sixteen about 0.05 percent, and the measured table shows both.
The filter is a set test, not a map: it cannot return values, list its keys or count them. It works best when most queries are negative, such as “is this key in this SSTable, before reading the disk block?” The implementation here sets m and k explicitly, stores the bits in a byte array numbered from the least significant bit, and derives the k indexes by double hashing.
How This Was Measured
| Setting | Value |
|---|---|
| Date tested | December 2, 2026 |
| Hardware | Intel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300 |
| Operating system | Ubuntu 24.04.5 under WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39, and Windows 11 for the MSVC build |
| Compilers | GCC 13.3 and Clang 18.1.3 at -O2 through CMake Release, MSVC 19.44 at /W4 /WX |
| Inserted keys | N = 100,000, keys 0 to 99,999 |
| Query keys | Q = 100,000 absent keys, 1,000,000 to 1,099,999 |
| Hash functions | splitmix64 double hashing: h1 = mix(key ^ 0x9E3779B97F4A7C15), h2 = mix(key ^ 0xBF58476D1CE4E5B9) with its lowest bit forced to 1, and index i = (h1 + i h2) mod m |
| Rows | 4, 8, 12 and 16 bits per key at k = 3, 6, 8 and 11, then 8 bits per key with k = 1 to 8 |
| Statistic | False positives among the Q absent queries, to six decimal places, against the formula at the same n, m and k |
| Check | The same keys, hashes and formatting in both languages, which must print identical tables |
The experiment is deterministic: the same keys and hashes set the same bits and give the same false-positive count on every run and in both languages. Each measured rate is still one sample of 100,000 queries, so it scatters around the formula by sampling noise.
Bits, Hashes and the Formula
The filter is one array of bytes and a bit count, laid out like any contiguous array in the Arrays article. Bit i lives in byte i / 8 under mask 1 << (i % 8), so setting a key’s k bits is k byte reads, ORs and writes. The memory is m/8 bytes. For 100,000 keys at 8 bits per key that is 100,000 bytes, a quarter of what the keys alone would take as 32-bit integers and far less than a hash set of them.
The hash functions are the other half of the design. A Bloom filter needs k indexes that are spread uniformly and behave independently, and computing k separate hashes is expensive. Double hashing takes two 64-bit hashes and forms index i = (h1 + i h2) mod m. Kirsch and Mitzenmacher showed that this gives the same asymptotic false-positive rate as k independent hashes. Forcing h2 odd is an extra safeguard: when m is a power of two, an odd step reaches every bit, as the fourth pitfall shows.
The formula’s shape shows in both experiments. At a fixed m and n, more hashes give a query more chances to hit a clear bit, but each insert also sets more bits, so the rate is U-shaped in k with its minimum at k = (m/n) ln 2. At a fixed k, more bits per key give every key more room, and the rate falls exponentially from four to sixteen bits per key.
Insert, Query and Why False Negatives Are Impossible
Insert computes the k indexes and sets the bits. It returns true if all k bits were already set, a hint that the key was probably present before. Query computes the same k indexes and returns true only if all are set. No key is ever compared, so two keys that hash to the same bits are indistinguishable, and an absent key that lands on bits set by other keys is a false positive.
False negatives are impossible by construction. Inserting a key sets all its bits, and no operation in the basic filter clears a bit, so a later query for that key finds all k set. The guarantee breaks only if something clears bits, through a deletion or a buggy clear, or computes indexes wrongly. The demo prints “false negatives: 0 of 4 inserted keys” for that reason.
Deletion is the missing operation. A counting filter keeps small counters instead of bits and decrements on delete, at a cost in memory. A cuckoo filter stores short fingerprints and supports deletion directly. For time-windowed data, two filters can alternate, with the older one cleared and reused. The basic filter is the right choice when the set only grows or a periodic rebuild is acceptable.
Choosing k and m
For a target false-positive rate p and n keys, sizing is arithmetic. The number of bits is m = -n ln p / (ln 2)^2, about 9.6 bits per key for a 1 percent target and 4.8 for 10 percent. The best hash count is k = (m/n) ln 2, about 7 for 1 percent and 3 for 10 percent. In practice the memory is chosen first, k is rounded to the nearest integer to (m/n) ln 2, and the resulting rate is the formula with that k.
At eight bits per key, the best k is 8 ln 2, about 5.5, so 5 and 6 are both good choices. Fewer hashes give a query too few chances to hit a clear bit. More hashes set so many bits that queries find them set anyway. At the best k, eight bits per key gives about 2.2 percent, matching the measurement, while four bits per key gives about 15 percent.
Each extra bit per key multiplies the rate by about 0.6185, and the memory stays at m bits whatever the size of the keys. A query costs two 64-bit hashes and k bit operations. A Bloom filter pays off when the alternative is a disk read or a network call and most queries are for absent keys.
What Bloom Filters Are Used For
The classic use is a pre-check in front of an expensive lookup. LevelDB, RocksDB and Cassandra keep a filter per data file, so a missing key is rejected without touching the disk. PostgreSQL ships a bloom index extension built on the same idea. A cache can also keep a filter in front of a slow store to reject requests for keys that are certainly absent.
The filter also appears in networking and security, in spelling checkers, weak-password blocklists and content routing. Redis offers a Bloom filter data type with the same insert and query semantics and no deletion, and the Wikipedia article covers the history and the variants.
The common thread is that a false positive costs one extra slow lookup, while a false negative would cost a wrong answer. The structure guarantees the second never happens and keeps the first at a measurable rate.
Bloom Filter Implementation in C
The C version is a struct with a byte array, a bit count and a hash count, plus the splitmix64 double-hashing helpers. The demo shows the set semantics with four keys, then clears the filter and checks that no key is reported present afterward.
static void bf_hash_pair(int key, uint64_t *h1, uint64_t *h2)
{
uint64_t widened = (uint64_t)key;
*h1 = bf_mix(widened ^ UINT64_C(0x9E3779B97F4A7C15));
*h2 = bf_mix(widened ^ UINT64_C(0xBF58476D1CE4E5B9)) | UINT64_C(1);
}
/* The i-th index of a key: the 64-bit sum wraps before the reduction. The
* remainder is a size_t, and the caller guarantees bit_count is not zero. */
static size_t bf_index(uint64_t h1, uint64_t h2, size_t i, size_t bit_count)
{
return (size_t)((h1 + (uint64_t)i * h2) % (uint64_t)bit_count);
}
/* Whether one bit of the array is set: bit i is bit i % 8 of byte i / 8. */
static bool bf_bit_is_set(const BloomFilter *filter, size_t index)
{
unsigned char mask = (unsigned char)(1u << (index % 8));
return (filter->bits[index / 8] & mask) != 0u;
}
/* Sets one bit and keeps the set-bit counter in step. */
static void bf_set_bit(BloomFilter *filter, size_t index)
{
unsigned char *byte = &filter->bits[index / 8];
unsigned char mask = (unsigned char)(1u << (index % 8));
if ((*byte & mask) == 0u) {
*byte |= mask;
filter->set_bits++;
}
}
bool bf_insert(BloomFilter *filter, int key)
{
uint64_t h1;
uint64_t h2;
size_t i;
bool present = true;
if (filter == NULL || filter->bits == NULL || filter->hash_count == 0)
return false;
bf_hash_pair(key, &h1, &h2);
for (i = 0; i < filter->hash_count; ++i) {
if (!bf_bit_is_set(filter, bf_index(h1, h2, i, filter->bit_count)))
present = false;
}
for (i = 0; i < filter->hash_count; ++i)
bf_set_bit(filter, bf_index(h1, h2, i, filter->bit_count));
filter->size++;
return present;
}
/* Whether every one of the key's k bits is set. A true answer means the key is
* probably present; a false answer means it is certainly absent. */
bool bf_contains(const BloomFilter *filter, int key)
{
uint64_t h1;
uint64_t h2;
size_t i;
if (filter == NULL || filter->bits == NULL || filter->hash_count == 0)
return false;
bf_hash_pair(key, &h1, &h2);
for (i = 0; i < filter->hash_count; ++i) {
if (!bf_bit_is_set(filter, bf_index(h1, h2, i, filter->bit_count)))
return false;
}
return true;
}
Output:
bloom filter: 64 bits, 3 hashes
insert 10, 20, 30 -> size 3
contains 10 -> true, contains 20 -> true, contains 30 -> true
insert 40 -> size 4
contains 40 -> true, size 4
bits 64, hashes 3, bits per key 16.00
false negatives: 0 of 4 inserted keys
clear -> size 0, bits set 0
after clear contains 10 -> false
Bloom Filter Implementation in C++
The C++ version is a class over a std::vector<unsigned char> with the same bit numbering, the same splitmix64 hashes and the same public operations. The demo prints the same lines as the C program, byte for byte.
bool insert(int key)
{
const std::uint64_t first = first_hash(key);
const std::uint64_t step = second_hash(key);
const bool probably_present = has_indexes(first, step);
for (std::size_t i = 0; i < hash_count_; ++i)
set(index(first, step, i));
++size_;
return probably_present;
}
// True when all k bits of the key are set. A false positive is possible; a
// false negative is not.
[[nodiscard]] bool contains(int key) const noexcept
{
return has_indexes(first_hash(key), second_hash(key));
}
// Zeroes every byte and resets size(). The filter is empty again.
void clear() noexcept
{
for (std::uint8_t& byte : bytes_)
byte = 0;
size_ = 0;
}
// Sets one bit with the contract layout: byte index / 8, mask 1 << (index % 8).
void set(std::size_t index) noexcept
{
const std::size_t byte = index / 8;
bytes_[byte] = static_cast<std::uint8_t>(bytes_[byte] |
static_cast<std::uint8_t>(1u << (index % 8)));
}
// The i-th index of the double-hash sequence, (h1 + i * h2) % m.
[[nodiscard]] std::size_t index(std::uint64_t first, std::uint64_t step,
Measured: False Positives Against the Formula
The false-positive experiment builds a fresh filter for each row, inserts the 100,000 keys, and queries the 100,000 absent keys, counting how many the filter reports present.
static bool run_row(const Row *row, size_t *false_positives_out)
{
BloomFilter filter;
size_t bit_count = (size_t)row->bits_per_key * (size_t)INSERTED;
size_t false_positives = 0;
size_t query;
double measured;
double theory;
double ratio;
int key;
if (!bf_init(&filter, bit_count, (size_t)row->hashes)) {
fputs("fpr_experiment: out of memory\n", stderr);
return false;
}
for (key = 0; key < INSERTED; ++key)
bf_insert(&filter, key);
for (query = 0; query < (size_t)QUERIED; ++query) {
if (bf_contains(&filter, ABSENT_FIRST + (int)query))
false_positives++;
}
measured = (double)false_positives / (double)QUERIED;
theory = pow(1.0 - exp(-((double)row->hashes * (double)INSERTED) /
(double)bit_count),
(double)row->hashes);
ratio = measured / theory;
printf("%-10d%-4d%-10.6f%-10.6f%.3f\n", row->bits_per_key, row->hashes,
measured, theory, ratio);
bf_free(&filter);
*false_positives_out = false_positives;
return true;
}
int main(void)
{
size_t sweep_counts[SWEEP_ROWS] = {0};
size_t sweep_filled = 0;
size_t row;
puts("false positives: N=100000 inserted, Q=100000 absent queries");
printf("%-10s%-4s%-10s%-10s%s\n", "bits/key", "k", "measured", "theory",
"ratio");
for (row = 0; row < sizeof ROWS / sizeof ROWS[0]; ++row) {
size_t false_positives = 0;
if (!run_row(&ROWS[row], &false_positives))
return EXIT_FAILURE;
if (row >= (size_t)SWEEP_FIRST_ROW) {
if (sweep_filled < (size_t)SWEEP_ROWS)
sweep_counts[sweep_filled] = false_positives;
sweep_filled++;
}
}
if (sweep_filled != (size_t)SWEEP_ROWS ||
!sweep_rises_past_minimum(sweep_counts)) {
fputs("fpr_experiment: the k sweep does not rise past its minimum\n",
stderr);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Output (C, identical in C++):
false positives: N=100000 inserted, Q=100000 absent queries
bits/key k measured theory ratio
4 3 0.147580 0.146892 1.005
8 6 0.021760 0.021577 1.008
12 8 0.003310 0.003142 1.053
16 11 0.000470 0.000459 1.025
8 1 0.115280 0.117503 0.981
8 2 0.048220 0.048929 0.986
8 3 0.031630 0.030579 1.034
8 4 0.024660 0.023969 1.029
8 5 0.021890 0.021679 1.010
8 6 0.021760 0.021577 1.008
8 7 0.022860 0.022930 0.997
8 8 0.026010 0.025492 1.020
The size rows track the formula closely. At 4 bits per key and 3 hashes the measured rate is 0.147580 against 0.146892, a ratio of 1.005. Eight bits per key and 6 hashes give 0.021760 against 0.021577 (1.008), 12 bits and 8 hashes give 0.003310 against 0.003142 (1.053), and 16 bits and 11 hashes give 0.000470 against 0.000459 (1.025). The ratios drift further from 1 as the rate shrinks because fewer false positives are counted: 0.003142 of 100,000 queries is about 314, so a 5 percent deviation is about one standard deviation of sampling noise.
Measured: Sweeping k
The k sweep at eight bits per key shows the formula’s U-shape directly: the rate falls from k = 1 to a minimum and rises again as k grows.
At k = 1 a query checks a single bit and the rate is 0.115280. Each added hash gives the query another chance to find a clear bit, and the rate falls to 0.021890 at k = 5 and a minimum of 0.021760 at k = 6. Beyond that, each insert sets so many bits that queries find them set anyway, and the rate rises to 0.026010 at k = 8, about a fifth above the minimum.
The formula follows the same path, from 0.117503 down to 0.021577 and up to 0.025492, and every measured point is within 3.4 percent of it. Rounding k one step from the optimum costs little, while being several steps off costs real false positives.
Five Ways a Bloom Filter Passes a Quick Test and Still Fails
Each program below compiles cleanly and prints something plausible until the wrong value appears or a sanitizer stops it. The three C pitfalls are in the C repository and the two C++ pitfalls in the C++ repository, and the workflows rerun each one and check its output line or its sanitizer summary.
1. A Bit Index That Escapes the Array
static void buggy_insert(unsigned char *bits, int key)
{
size_t h1;
size_t h2;
size_t i;
hashes_of(key, &h1, &h2);
for (i = 0; i < FILTER_HASHES; ++i) {
size_t index = h1 + i * h2;
if (i + 1 < FILTER_HASHES)
index %= FILTER_BITS;
bits[index / 8] |= (unsigned char)(1u << (index % 8));
}
}
int main(void)
{
volatile size_t allocated_bytes = FILTER_BYTES;
unsigned char *bits = bits_new(allocated_bytes);
size_t h1;
size_t h2;
size_t last_index;
size_t last_byte;
setvbuf(stdout, NULL, _IONBF, 0);
if (bits == NULL) {
fputs("bit_index_out_of_bounds: out of memory\n", stderr);
return EXIT_FAILURE;
}
puts("bit_index_out_of_bounds: a 64-bit filter allocates 8 bytes");
hashes_of(DEMO_KEY, &h1, &h2);
last_index = h1 + (FILTER_HASHES - 1) * h2;
last_byte = last_index / 8;
printf("key %d: the last index skips the modulo and is %zu\n", DEMO_KEY,
last_index);
printf("bit %zu lives at byte %zu of the %d-byte array\n", last_index,
last_byte, FILTER_BYTES);
puts("the insert reads and marks that byte next");
buggy_insert(bits, DEMO_KEY);
puts("the write past the array did not fail loudly");
free(bits);
return EXIT_SUCCESS;
}
Output:
bit_index_out_of_bounds: a 64-bit filter allocates 8 bytes
key 0: the last index skips the modulo and is 125
bit 125 lives at byte 15 of the 8-byte array
the insert reads and marks that byte next
AddressSanitizer stops the insert. Its report, summarized:
ERROR: AddressSanitizer: heap-buffer-overflow
READ of size 1 in buggy_insert (pitfalls/bit_index_out_of_bounds.c:71)
7 bytes after the 8-byte region allocated by bits_new (pitfalls/bit_index_out_of_bounds.c:78)
SUMMARY: AddressSanitizer: heap-buffer-overflow pitfalls/bit_index_out_of_bounds.c:71 in buggy_insert
One index skips the modulo, so in a 64-bit filter the bad index is 125 while the array holds 8 bytes. Bit 125 lives in byte 15, seven bytes past the allocation. Setting a bit reads the byte before writing it, so the first bad access is the read, and AddressSanitizer reports a heap-buffer-overflow read of size 1, 7 bytes after the 8-byte region. The fix is the modulo, not a bounds check: every index must be reduced into [0, m) before it is used.
2. A Mask Shifted by the Whole Index
static void buggy_set(unsigned char *bits, size_t index)
{
bits[index / 8] |= (unsigned char)(UINT64_C(1) << index);
}
static bool buggy_contains(const unsigned char *bits, size_t index)
{
return (bits[index / 8] & (unsigned char)(UINT64_C(1) << index)) != 0u;
}
static void correct_set(unsigned char *bits, size_t index)
{
bits[index / 8] |= (unsigned char)(1u << (index % 8));
}
static bool correct_contains(const unsigned char *bits, size_t index)
{
return (bits[index / 8] & (unsigned char)(1u << (index % 8))) != 0u;
}
int main(void)
{
unsigned char buggy_bits[FILTER_BYTES] = {0};
unsigned char correct_bits[FILTER_BYTES] = {0};
int buggy_misses;
int correct_misses;
buggy_misses = count_false_negatives(buggy_bits, true);
correct_misses = count_false_negatives(correct_bits, false);
puts("wrong_bit_mask: a 64-bit filter, 3 hashes, 20 inserted keys");
puts("the mask is 1ull << index instead of 1ull << (index % 8), so every "
"index of 8 or more shifts out of the byte");
printf("buggy filter: set bits %zu, false negatives %d of %d inserted "
"keys\n", popcount(buggy_bits), buggy_misses,
(int)INSERTED_KEYS);
printf("correct filter: set bits %zu, false negatives %d of %d inserted "
"keys\n", popcount(correct_bits), correct_misses,
(int)INSERTED_KEYS);
return EXIT_SUCCESS;
}
Output:
wrong_bit_mask: a 64-bit filter, 3 hashes, 20 inserted keys
the mask is 1ull << index instead of 1ull << (index % 8), so every index of 8 or more shifts out of the byte
buggy filter: set bits 2, false negatives 20 of 20 inserted keys
correct filter: set bits 36, false negatives 0 of 20 inserted keys
The broken mask shifts by the whole index, 1 << index, instead of by the position inside the byte, 1 << (index % 8). For any index of 8 or more, the shifted value’s low byte is zero, so the store changes nothing and the query reads a clear bit. The buggy filter ends with 2 set bits for 20 inserted keys, and all 20 queries for those keys report absent: 20 false negatives, which a correct filter makes impossible. The correct filter sets 36 bits and reports none.
3. A Second Hash That Does Not Move
static size_t filter_index(const PitfallFilter *filter, int key, size_t i,
bool constant_second)
{
uint64_t h1 = mix((uint64_t)key ^ UINT64_C(0x9E3779B97F4A7C15));
uint64_t h2 = constant_second
? (uint64_t)CONSTANT_SECOND_HASH
: mix((uint64_t)key ^ UINT64_C(0xBF58476D1CE4E5B9)) |
UINT64_C(1);
return (size_t)((h1 + (uint64_t)i * h2) % (uint64_t)filter->bit_count);
}
static void filter_insert(PitfallFilter *filter, int key, bool constant_second)
{
size_t i;
for (i = 0; i < HASHES; ++i)
filter_set(filter, filter_index(filter, key, i, constant_second));
}
static bool filter_contains(const PitfallFilter *filter, int key,
bool constant_second)
{
size_t i;
for (i = 0; i < HASHES; ++i) {
if (!filter_get(filter, filter_index(filter, key, i, constant_second)))
return false;
}
return true;
}
static bool run(const char *label, bool constant_second)
{
PitfallFilter filter;
size_t bit_count = (size_t)BITS_PER_KEY * (size_t)INSERTED;
size_t false_positives = 0;
size_t query;
double measured;
double theory;
double ratio;
int key;
if (!filter_init(&filter, bit_count)) {
fputs("constant_second_hash: out of memory\n", stderr);
return false;
}
for (key = 0; key < INSERTED; ++key)
filter_insert(&filter, key, constant_second);
for (query = 0; query < (size_t)QUERIED; ++query) {
if (filter_contains(&filter, ABSENT_FIRST + (int)query,
constant_second))
false_positives++;
}
measured = (double)false_positives / (double)QUERIED;
theory = pow(1.0 - exp(-((double)HASHES * (double)INSERTED) /
(double)bit_count),
(double)HASHES);
ratio = measured / theory;
printf("%s set bits %zu, measured %.6f, formula %.6f, ratio %.3f\n",
label, filter.set_bits, measured, theory, ratio);
filter_free(&filter);
return true;
}
Output:
constant_second_hash: h2 = 1, so the k indexes are adjacent bits
N=100000 inserted, Q=100000 absent queries, bits/key 8, k 6
constant h2: set bits 422294, measured 0.246250, formula 0.021577, ratio 11.413
mixed h2: set bits 422516, measured 0.021760, formula 0.021577, ratio 1.008
A constant second hash of 1 turns the k indexes into k adjacent bits. The filter sets almost exactly as many bits as the correct one, 422,294 against 422,516, but each query’s bits are now neighbors and therefore correlated. The broken filter measures 0.246250 against the formula’s 0.021577, 11.4 times too high, while the correct mixed hash measures 0.021760. The set-bit count alone would never reveal the problem, which is why comparing the measured rate with the formula is the useful check.
4. A Step That Can Only Reach Half the Bits
std::uint64_t second_hash(int key, bool force_even) noexcept
{
std::uint64_t step = mix(static_cast<std::uint64_t>(key) ^ kHashSalt2) | 1ULL;
if (force_even)
step &= ~1ULL;
return step;
}
void insert(int key)
{
const std::uint64_t first = first_hash(key);
const std::uint64_t step = second_hash(key, even);
for (std::size_t i = 0; i < hash_count; ++i) {
const std::size_t slot =
static_cast<std::size_t>((first + static_cast<std::uint64_t>(i) * step) % bit_count);
bytes[slot / 8] = static_cast<std::uint8_t>(
bytes[slot / 8] | static_cast<std::uint8_t>(1u << (slot % 8)));
}
++size;
}
int main()
{
Filter correct(kBits, kHashes, false);
Filter buggy(kBits, kHashes, true);
for (std::size_t key = 0; key < kInserted; ++key) {
correct.insert(static_cast<int>(key));
buggy.insert(static_cast<int>(key));
}
const std::size_t correct_reachable = correct.reachable_count(kProbeKey);
const std::size_t buggy_reachable = buggy.reachable_count(kProbeKey);
std::size_t correct_false_positives = 0;
std::size_t buggy_false_positives = 0;
const double correct_rate = false_positive_rate(correct, correct_false_positives);
const double buggy_rate = false_positive_rate(buggy, buggy_false_positives);
const double theory =
std::pow(1.0 - std::exp(-(static_cast<double>(kHashes) * static_cast<double>(kInserted)) /
static_cast<double>(kBits)),
static_cast<double>(kHashes));
std::cout << "even_step_hash: a power-of-two bit count with an even second hash\n";
std::cout << "bits " << kBits << ", hashes " << kHashes << ", inserted keys " << kInserted
<< ", absent queries " << kQueries << '\n';
std::cout << "reachable bit indexes for key " << kProbeKey << ": correct " << correct_reachable
<< ", buggy " << buggy_reachable << " of " << kBits << '\n';
std::cout << "set bits: correct " << correct.set_bits() << ", buggy " << buggy.set_bits()
<< " of " << kBits << '\n';
std::cout << "measured false positive rate: correct " << std::fixed << std::setprecision(6)
<< correct_rate << ", buggy " << buggy_rate << '\n';
std::cout << "theory false positive rate: " << theory << '\n';
std::cout << "violated invariant: an even step keeps every key in one parity class, so half "
"the bit space is unreachable\n";
if (correct_reachable != kBits || buggy_reachable != kBits / 2) {
std::cerr << "the reachability measurement did not show the halved bit space\n";
return EXIT_FAILURE;
}
if (correct.set_bits() == 0 || buggy.set_bits() == 0 || buggy_false_positives == 0) {
std::cerr << "the filters did not produce the expected set bits and false positives\n";
return EXIT_FAILURE;
}
std::cout.flush();
return EXIT_SUCCESS;
}
Output:
even_step_hash: a power-of-two bit count with an even second hash
bits 1048576, hashes 3, inserted keys 20000, absent queries 1000000
reachable bit indexes for key 0: correct 1048576, buggy 524288 of 1048576
set bits: correct 58301, buggy 58325 of 1048576
measured false positive rate: correct 0.000172, buggy 0.000168
theory false positive rate: 0.000172
violated invariant: an even step keeps every key in one parity class, so half the bit space is unreachable
With a power-of-two bit count and an even step, every index of a key keeps the parity of h1, so the key can reach only half the array: 524,288 of 1,048,576 bits. In this run the rate barely moves, 0.000168 broken against 0.000172 correct, because the keys split evenly between the two parity classes and each half fills at the same density as the whole. The real danger is a step with more factors of two. A step divisible by m makes all k indexes identical, which turns a k-hash filter into a one-hash filter. Forcing the step odd rules out the whole family.
5. A Clear That Only Clears One Byte
void clear_all() noexcept
{
for (std::uint8_t& byte : bytes)
byte = 0;
size = 0;
}
// The bug: only the first byte goes to zero. The other bytes keep the bits
// the last contents set.
void clear_first_byte_only() noexcept
{
if (!bytes.empty())
bytes[0] = 0;
size = 0;
}
int main()
{
Filter correct(kBits, kHashes);
Filter buggy(kBits, kHashes);
for (std::size_t key = 0; key < kInserted; ++key) {
correct.insert(static_cast<int>(key));
buggy.insert(static_cast<int>(key));
}
const std::size_t bits_before_clear = correct.set_bits();
correct.clear_all();
buggy.clear_first_byte_only();
const std::size_t correct_bits_after_clear = correct.set_bits();
const std::size_t buggy_bits_after_clear = buggy.set_bits();
const std::size_t correct_false_positives = count_false_positives(correct);
const std::size_t buggy_false_positives = count_false_positives(buggy);
const double correct_rate =
static_cast<double>(correct_false_positives) / static_cast<double>(kQueries);
const double buggy_rate =
static_cast<double>(buggy_false_positives) / static_cast<double>(kQueries);
std::cout << "partial_clear: clear zeroes only the first byte of the bit array\n";
std::cout << "bits " << kBits << ", hashes " << kHashes << ", inserted keys " << kInserted
<< ", absent queries " << kQueries << '\n';
std::cout << "bit array bytes: " << correct.bytes.size()
<< ", zeroed by the buggy clear: 1\n";
std::cout << "set bits before clear: " << bits_before_clear << '\n';
std::cout << "set bits after clear: correct " << correct_bits_after_clear << ", buggy "
<< buggy_bits_after_clear << '\n';
std::cout << "measured false positive rate after clear: correct " << std::fixed
<< std::setprecision(6) << correct_rate << ", buggy " << buggy_rate << '\n';
std::cout << "violated invariant: clear must zero every byte of the bit array\n";
if (bits_before_clear == 0 || correct_bits_after_clear != 0 || buggy_bits_after_clear == 0 ||
correct_false_positives != 0 || buggy_false_positives == 0) {
std::cerr << "the clear measurement did not show the stale bits\n";
return EXIT_FAILURE;
}
std::cout.flush();
return EXIT_SUCCESS;
}
Output:
partial_clear: clear zeroes only the first byte of the bit array
bits 1048576, hashes 3, inserted keys 200000, absent queries 1000000
bit array bytes: 131072, zeroed by the buggy clear: 1
set bits before clear: 457140
set bits after clear: correct 0, buggy 457136
measured false positive rate after clear: correct 0.000000, buggy 0.082493
violated invariant: clear must zero every byte of the bit array
The broken clear zeroes only the first byte of the 131,072-byte array. Before the clear the filter holds 457,140 set bits. After the correct clear it holds 0, while after the broken one it still holds 457,136, and absent keys get a false-positive rate of 0.082493 instead of 0.000000. A filter that looks empty but is not answers “probably present” for keys it never saw.
Key Takeaways
- A Bloom filter is a bit array with k hash functions: insert sets k bits, query checks all k, and any clear bit proves absence.
- False negatives are impossible, and false positives follow (1 – e^(-kn/m))^k.
- The best hash count is k = (m/n) ln 2, and each extra bit per key multiplies the rate by about 0.6185.
- With 100,000 keys, 8 bits per key and 6 hashes gave 0.021760 against the formula’s 0.021577, and 16 bits per key gave 0.000470 against 0.000459.
- The k sweep at eight bits per key is U-shaped, with its minimum at k = 6 and k = 5 almost equal, as the formula predicts.
- The filter trades keys for bits: it cannot list, count or delete keys, but it is tiny and fast, which is why databases and caches use it as a pre-check.
Frequently Asked Questions
Conclusion
The Bloom filter is a compact answer to a narrow question. One bit array, k indexes from two hashes, and a formula that predicts the failure rate: the measured run matched it across four sizes, from 0.147580 at four bits per key to 0.000470 at sixteen, and the k sweep traced the full U with its minimum at k = 6. There are no false negatives, and the false positives are the price of storing no keys at all.
The data structures hub places the filter beside the exact structures. In production, size the filter from the formula, keep the hash count near (m/n) ln 2, plan for rebuilds rather than deletions, and keep the bit-index arithmetic under test, because the pitfalls show how one wrong index or mask turns a filter into a source of false negatives.
Source Code and Tests
The programs on this page are in the data-structures/bloom-filter directory of two MYCPLUS example repositories:
| Language | Repository directory | Build status |
|---|---|---|
| C | mycplus/c-examples: data-structures/bloom-filter | |
| C++ | mycplus/cpp-examples: data-structures/bloom-filter |
The examples build and test with CMake:
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure
The demo’s output is compared byte for byte with tests/expected/ordered.txt. The tests check inserts, queries, the bit count, the set-bit count, clearing and the no-false-negative property over random keys, and verify the experiment’s exact output. The workflows also run the tests and pitfalls under AddressSanitizer and UndefinedBehaviorSanitizer, and the out-of-bounds pitfall must produce its sanitizer summary.
What I Verified
The example directories contain the test programs and the captured runs. The table states which system ran each check.
| Check | Ubuntu 24.04 (WSL2) | Windows 11 (MSVC) |
|---|---|---|
| Build and tests, C, GCC 13.3, C11 and C17 | Pass (7 of 7 tests) | Not applicable |
| Build and tests, C, Clang 18.1.3, C11 and C17 | Pass (7 of 7 tests) | Not applicable |
Build and tests, C, MSVC 19.44 /W4 /WX | Not applicable | Pass (7 of 7 tests) |
| Build and tests, C++, g++ 13.3, C++17 and C++20 | Pass (5 of 5 tests) | Not applicable |
| Build and tests, C++, clang++ 18.1.3, C++17 and C++20 | Pass (5 of 5 tests) | Not applicable |
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive- | Not applicable | Pass (5 of 5 tests, C++17 and C++20) |
| AddressSanitizer and UndefinedBehaviorSanitizer, tests, demo and pitfalls | Pass (C 7 of 7, C++ 5 of 5) | Not applicable |
| Five pitfalls, each caught by its check or sanitizer summary | Pass (4 output checks, 1 AddressSanitizer summary) | Not applicable |
| False-positive experiment, C and C++ | Run, identical tables, output above | Not run |
| Independent rerun on a second Linux x86-64 machine (GCC 13.3, Clang 18.1.3) | Pass (C 7 of 7 and C++ 5 of 5 with both compilers, C under ASan and UBSan 7 of 7, demo, table and all five pitfalls identical to the captures) | Not applicable |
Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, macOS, counting or cuckoo variants, other hash families, and other key sets.




