1

This is driving me crazy. I have legacy code where I added few more conditions (below). I am parsing a string and retrieving the data. This is how it is done in legacy code so I haven't changed the style.

        WORD wPSM = 0;
        double dblPST = 0;
        WORD wSDB = 0;

        if(-1 != str.Find("PSM="))
        {
            nNumScanned = sscanf_s((LPCTSTR) str, "PSM=%u", &wPSM);
        }
        if(-1 != str.Find("PST="))
        {
            nNumScanned = sscanf_s((LPCTSTR) str, "PST=%lf", &dblPST);
        }
        if(-1 != str.Find("SDB="))
        {
            nNumScanned = sscanf_s((LPCTSTR) str, "SDB=%u", &wSDB);
        }

I get error Run-Time Check Failure #2 - Stack around the variable 'wPSM' was corrupted. I don't get this error if I commented these three lines. str is CString and it does contain the expected value.

Is there something wrong with sscanf_s syntax above that maybe causing this?

Note this is c++ project with VS2010, I have marked it C only to draw attention because of sscanf_s

5
  • There is no wPST variable in the code you show.
    – sth
    Oct 7, 2014 at 14:37
  • a) which 3 lines? b) where is wPST declared, it's not in your snippet
    – Tom Tanner
    Oct 7, 2014 at 14:38
  • 2
    You're scanning with %u (and so, likely, collecting 32 bits of data - if not 64 bits) into a WORD (16-bit) variable. Those extra 16 bits are going into a part of the stack where they don't belong.
    – Paul Roub
    Oct 7, 2014 at 14:38
  • Bit OT, but I don't think the C tag is relevant despite your usage of sscanf_s. First, it's a Windows-specific function, and second, this is C++ code. Oct 7, 2014 at 14:40
  • corrected wPST reference, sorry had shortened the actual names for public post.
    – zar
    Oct 7, 2014 at 14:40

1 Answer 1

4

WORD is a define for a 16 bits unsigned integer, so your program has undefined behaviour since sscanf_s expects an unsigned integer.

You need the %hu modifier in your calls to sscanf_s.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.