Search code examples
c++bufferbuffer-overrun

buffer overrun happens in SystemTimeToVariantTime


void ConvertDateIntoSystemFormat(std::wstring dateModified,DATE& date)
{
SYSTEMTIME systemTime;

memset(&systemTime, 0, sizeof(systemTime));

sscanf_s(ConvertWstringToCharStar(dateModified), "%d-%d-%dT%d:%d:%d.%dZ",
    &systemTime.wYear, &systemTime.wMonth, &systemTime.wDay, &systemTime.wHour, &systemTime.wMinute, &systemTime.wSecond, &systemTime.wMilliseconds);

SystemTimeToVariantTime(&systemTime, &date);
}

Here is my code. It will convert a wstring which contains date and time intoDATE type. However, when I run this part of code, it always throw exceptions says "buffer overrun" when the debugger is leaving this function scope. I alsy tried to chnage it to void ConvertDateIntoSystemFormat(std::wstring dateModified,DATE* date) and try to allocate memeory for date when pass it to this function or tried use LPSYSTEMTIME instead of SYSTEMTIME, or tried DATE ConvertDateIntoSystemFormat(std::wstring dateModified) with declare DATE date inside the function but none of them works, the buffer overrun problem still happens. How to fix this problem?

enter image description here


Solution

  • All SYSTEMTIME fields have WORD type (aka short) while format %d expects a pointer to an int. Fix format string by using %hd.