Skip to content

Crash Due to Invalid Iterator Dereference in BFS Implementation #309

@wuxianggujun

Description

@wuxianggujun

Description
The BFS algorithm crashes with an "Exception 0x80000003" (access violation) and an assertion failure "cannot dereference end list iterator" during graph traversal. The crash occurs specifically when processing queue elements and accessing the graph structure.

Reproduction Steps

  1. Build and execute the provided BFS implementation
  2. Initialize graph with the test data:
    graph.insert({"you", {"alice", "bob", "claire"}});
    ... // Other nodes
  3. Start search from node "you"
  4. Program crashes during queue processing

Error Log

Exception 0x80000003 encountered at address 0x7ff6f69aba73
File: MSVC include\list Line: 147  
Expression: cannot dereference end list iterator

Root Cause Analysis

  1. Dangling Reference

    • Original code used T& person = search_queue.front() followed by pop()
    • Created invalid reference to queue data after element removal
    • Subsequent access to person caused undefined behavior
  2. Unsafe Iterator Dereference

    • Direct dereference of graph.find()->second without existence check
    • Risk of accessing end() iterator when key not found
  3. Incomplete Graph Validation

    • No validation for node existence when processing friends lists
    • Potential null-dereference for missing graph nodes

Proposed Fix

// 1. Safe queue element access
T person = search_queue.front(); // Copy instead of reference
search_queue.pop();

// 2. Validate graph nodes before access
auto start_it = graph.find(name);
if (start_it == graph.end()) {
    return false; // Handle missing start node
}

// 3. Secure friend list processing
auto person_it = graph.find(person);
if (person_it != graph.end()) {
    for (const auto& friend_name : person_it->second) {
        search_queue.push(friend_name);
    }
}

Verification
After applying these changes:

  • Test case successfully finds "thom" as mango seller
  • Stress tests with missing nodes no longer crash
  • Valgrind/memory checks show clean reports

Severity: Critical (Crash/Data Corruption)
Priority: P1 (Must Fix)
Affected Versions: All versions prior to 2023-04-07

Suggested Additional Improvements

  1. Add unit tests for:
    • Missing start node
    • Nodes with empty friend lists
    • Multiple consecutive sellers
  2. Implement graph validation wrapper
  3. Add error logging for missing nodes

Environment

  • OS: Windows 10/11
  • Compiler: MSVC 2022 (v14.34-17.8)
  • Build Config: Debug x64
  • STL Version: MSVC STL 2022

Attachments

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions