The stack around the variable was corrupted after typing unsigned char with scanf

#include <stdio.h>
int main()
{
    unsigned char y;
    scanf("%hhu", &y);
    printf("%hhu", y);
    return 0;
}

      

This code works fine with g ++ (Dev C ++) but causes stack corruption in Visual Studio (2010), is this a VS bug or is there any other way to input unsigned char

into VS with scanf();

?

+3


source to share


2 answers


Looks like VS is not handling %hhu

: fooobar.com/questions/1473606 / ...



The important detail is that you are using Windows and a supposedly outdated or non-compliant C environment (compiler and standard library). MSVCRT only supports C89 (and even then, not entirely correct); in particular, C89 did not have the "hh" modifier, and he probably interpreted "hh" the same as "h" (ie short).

+5


source


Just add a little more detail ...

Corruption happens around line 1111 in input.c.

if ( integer64 )
  *(__int64 UNALIGNED *)pointer = (unsigned __int64)num64;
else
if (longone)
  *(long UNALIGNED *)pointer = (unsigned long)number;
else
  *(short UNALIGNED *)pointer = (unsigned short)number;

      

You can see that there is no case where only 8 bits will be written.

When parsing a format string, the counter is longone

initially set to 1 and is decremented each time an "h" is encountered. Later (in the above snippet) is longone

used as a flag to determine if the parsed integer is 32 bits or not.

This behavior is fine if used "%hu"

, since it longone

will be 0 and therefore the parsed value will be treated as 16 bits. If, however "%hhu"

, longone

it will be equal to -1, and therefore analyte value is regarded as 32 bits.



Either way (32 or 16 bits) your char pointer will have more than the expected 1 byte, resulting in stack corruption.

This behavior affects all related functionality scanf()

as Visual Studio implements things like swscanf_s()

making an input string look like a file descriptor. So everything ends up with a function _tinput_s_l()

(line 368 in input.c) where the above problem manifests itself.

The MSDN documentation for Visual Studio 2010 shows the prefix %h

, but not the prefix %hh

.

What's new for Visual C ++ in Visual Studio 2015 says that:

C99 Compliance Visual Studio 2015 fully implements the C99 Library standard, with the exception of any library functions that depend on compiler functions are not yet supported by the Visual C ++ compiler (for example, <tgmath.h>

not implemented).

Which I read as "we have implemented everything except the bits that we don't have, which we won't talk about."

+1


source







All Articles