fix: strtok mutates c_str() via const cast - #14
Open
andrewwhitecdw wants to merge 1 commit into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
fix: avoid UB when strtok mutates c_str() via const cast
Summary
parsePartitionIdlistString()infmpm.cpptokenizes a comma-separated partition list withstrtok, but passes the pointer returned bystd::string::c_str()after casting away itsconstqualifier. Becausestrtokwrites into its first argument, this is undefined behavior and can lead to silent corruption or crashes depending on the implementation ofstd::string.Root cause
std::string::c_str()returnsconst char *:strtokmutates the input buffer to insert null terminators between tokens. Casting awayconstdoes not change the fact that the underlying storage was obtained as read-only throughc_str(), so any write through that pointer is UB. Most implementations happen to make it work today, but it is not guaranteed and can break with different compilers,-D_GLIBCXX_DEBUG, or custom allocators.Fix
Use
&partitionListStr[0]to obtain a mutable pointer to the string's contiguous internal buffer (contiguity and mutability are guaranteed forstd::stringsince C++11):This preserves the existing parsing behavior while removing the undefined const cast. An empty input string still causes
strtokto returnNULLon the first call and the loop exits with*numPartitions = 0, matching the original observable behavior.Testing
fmpm.cpp. If maintainers would like a test added, I am happy to add one in whatever form the project prefers.Why existing tests missed it
This is a C-level undefined-behavior issue in a utility function; it would not be caught by build or lint checks unless a sanitizer/UBSan run is executed against this code path, which does not appear to be part of CI.