Skip to content

Conversation

@svc-rdkeportal01
Copy link

Issue Fixed

Coverity Defect: DIVIDE_BY_ZERO
CWE: CWE-369 (Divide By Zero)
Severity: High
Function: rtHashMap_Hash_Func_String
File: src/rtmessage/rtHashMap.c

Root Cause

The function rtHashMap_Hash_Func_String computes a hash value and uses modulo to map it to a bucket:

return abs(hash) % rtVector_Size(hashmap->buckets);

If rtVector_Size(hashmap->buckets) returns 0 (empty buckets vector), this causes a divide by zero error, which will crash the program.

Changes Made

Before (Buggy):

while(*skey)
{
    hash = hash * 31 + *skey;
    skey++;
}
return abs(hash) % rtVector_Size(hashmap->buckets);  // ❌ Can divide by zero!

After (Fixed):

while(*skey)
{
    hash = hash * 31 + *skey;
    skey++;
}
size_t buckets_size = rtVector_Size(hashmap->buckets);
if(buckets_size == 0)  // ✅ Check for zero
    return 0;
return abs(hash) % buckets_size;  // ✅ Safe to divide

Why This Fix is Correct

  1. Prevents crash - Checks for zero before division
  2. Reasonable fallback - Returns 0 when buckets are empty (no valid bucket index exists)
  3. Minimal change - Just adds a safety check
  4. Performance - Negligible overhead (one comparison)

Edge Case Handling

When does buckets_size == 0?

  • HashMap is newly created but not initialized
  • HashMap has been cleared/destroyed
  • Corrupted state

Why return 0?

  • When there are no buckets, there's no valid bucket index
  • Returning 0 is a safe default (will be handled by caller)
  • Prevents undefined behavior from division by zero

Testing

  • Verified fix compiles without errors
  • Checked that zero case is properly handled
  • Confirmed normal operation is unaffected

The function rtHashMap_Hash_Func_String performs a modulo operation with
rtVector_Size(hashmap->buckets) without checking if the size is zero.
This can cause a divide by zero error if the buckets vector is empty.

This fix checks if buckets_size is zero before performing the modulo
operation and returns 0 in that case.

Coverity: DIVIDE_BY_ZERO
CWE-369: Divide By Zero
@svc-rdkeportal01 svc-rdkeportal01 requested a review from a team as a code owner December 4, 2025 20:24
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.

1 participant