SystemTimeToVariantTime发生缓冲区溢出,求排查(附日期转换函数代码)
Fixing Buffer Overflow in
SystemTimeToVariantTime Let’s break down what’s causing that buffer overflow and fix your code step by step:
Key Issues in Your Original Code
- Mismatched Format Specifiers: Every member of
SYSTEMTIMEis aWORD(an alias forunsigned short), but you’re using%d(the format specifier for 4-byteint) withsscanf_s. When the function tries to write a fullintvalue into a 2-byteWORDvariable, it overruns theSYSTEMTIMEstructure’s memory. This corruption triggers the buffer overflow whenSystemTimeToVariantTimetries to read the damaged data. - Risky Wide-to-Narrow Conversion: Using
ConvertWstringToCharStarintroduces unnecessary complexity—if this function doesn’t allocate memory correctly or returns a pointer to temporary data, you could end up parsing garbage values that worsen the overflow. - No Error Checking: You aren’t verifying if
sscanf_ssuccessfully parsed all date fields, so invalid input could lead to partial writes that corrupt theSYSTEMTIMEstructure.
Fixed Code Implementation
Here’s a revised, safer version of your function:
#include <wchar.h> #include <stdexcept> void ConvertDateIntoSystemFormat(const std::wstring& dateModified, DATE& date) { // Initialize SYSTEMTIME to zero with C++ initializer list (cleaner than memset) SYSTEMTIME systemTime = {0}; // Use swscanf_s to handle wide strings directly—no need for conversion int parsedFieldCount = swscanf_s( dateModified.c_str(), L"%hu-%hu-%huT%hu:%hu:%hu.%huZ", &systemTime.wYear, &systemTime.wMonth, &systemTime.wDay, &systemTime.wHour, &systemTime.wMinute, &systemTime.wSecond, &systemTime.wMilliseconds ); // Ensure all 7 date/time fields were parsed correctly if (parsedFieldCount != 7) { throw std::invalid_argument("Input doesn't match ISO 8601 format (YYYY-MM-DDTHH:MM:SS.sssZ)"); } // Validate the conversion to DATE type if (!SystemTimeToVariantTime(&systemTime, &date)) { throw std::runtime_error("Failed to convert system time to DATE variant"); } }
What Changed & Why
- Switched to
swscanf_s: This wide-character scan function works directly withstd::wstring(viac_str()), eliminating the need for risky wide-to-narrow string conversion. - Corrected Format Specifiers:
%huis the proper format forunsigned short(akaWORD), so we no longer write beyond the bounds of eachSYSTEMTIMEmember. - Safer Initialization: Using
SYSTEMTIME systemTime = {0};is more idiomatic C++ and ensures all structure members start at zero without relying onmemset. - Added Error Checking: We verify that all date fields are parsed, and that the final conversion to
DATEsucceeds. This catches invalid input before it causes memory issues. - Const Reference Parameter: Changing
dateModifiedto aconst std::wstring&avoids unnecessary string copies and guarantees we don’t modify the input.
Bonus: Optional Validation
For extra robustness, you can add checks for valid date values (e.g., months 1-12, days matching the month) before calling SystemTimeToVariantTime—this prevents invalid SYSTEMTIME values from causing unexpected behavior.
内容的提问来源于stack exchange,提问作者beasone
相关产品推荐
相关产品推荐

