Skip to content

fix: add sscanf return value check to prevent uninitialized value return#286

Open
hobostay wants to merge 1 commit intodeepseek-ai:mainfrom
hobostay:fix/sscanf-return-value-check
Open

fix: add sscanf return value check to prevent uninitialized value return#286
hobostay wants to merge 1 commit intodeepseek-ai:mainfrom
hobostay:fix/sscanf-return-value-check

Conversation

@hobostay
Copy link

@hobostay hobostay commented Feb 9, 2026

Summary

This PR fixes a potential bug in csrc/utils/system.hpp where the return value of std::sscanf was not being checked when parsing integer environment variables.

Problem

In the get_env<int>() function template, std::sscanf was used to parse an environment variable string as an integer, but the return value was never checked. If the environment variable contains a value that cannot be parsed as an integer (e.g., "abc", "12.3", or an empty string), sscanf fails and the value variable remains uninitialized. This uninitialized value is then returned, leading to undefined behavior.

Solution

Added a check for sscanf's return value (which should be 1 for successful parsing of one integer). If parsing fails, the function now returns the provided default value instead of the uninitialized variable.

Changes

// Before: Uninitialized value returned on sscanf failure
} else if constexpr (std::is_same_v<dtype_t, int>) {
    int value;
    std::sscanf(c_str, "%d", &value);
    return value;
}

// After: Returns default value on parsing failure
} else if constexpr (std::is_same_v<dtype_t, int>) {
    int value;
    if (std::sscanf(c_str, "%d", &value) != 1) {
        // Failed to parse as int, return default value
        return default_value;
    }
    return value;
}

Test plan

  • Code compiles successfully
  • No behavior change for valid integer environment variables
  • Graceful handling of invalid integer environment variables (returns default instead of UB)
  • Minimal code change, focused fix

Impact

  • Fixes potential undefined behavior when environment variables contain invalid integer values
  • Makes the function more robust and predictable
  • No breaking changes to API or behavior for valid inputs

🤖 Generated with Claude Code

- Check sscanf return value when parsing int from environment variable
- Return default value if parsing fails instead of returning uninitialized value
- This prevents potential undefined behavior when env var contains invalid integer

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
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