0

Look at the following simple piece of code

int main() 
{
   short x = 0, y = 0;
   scanf("%d", &x);
   scanf("%d", &y);
   printf("%d %d\n", x, y);
   return 0;
}

If you input 4 and 5 to this program, you'd expect to get 4 and 5 in the output. With GCC 4.6.2 on windows (mingw), it produces 0 and 5 as the output. So I dug up a bit. This is the assembly code generated

movw    $0, 30(%esp)
movw    $0, 28(%esp)
leal    30(%esp), %eax
movl    %eax, 4(%esp)
movl    $LC0, (%esp)
call    _scanf
leal    28(%esp), %eax
movl    %eax, 4(%esp)
movl    $LC0, (%esp)
call    _scanf

While I haven't done much assembler coding, the above code does not look right. It seems to suggest that x is placed at an offset of 30 bytes of the esp, and y is placed at an offset of 28 bytes of the esp, and then their addresses are passed to scanf. So, when the addresses of x and y are dealt as long ints (4 byte addresses), the following should happen: The first call would set the bytes [30,34) to the value 0x00000004, and the second call would set the bytes [28, 32) to the value 0x00000005. However, since this is a little endian machine, we would have the [0x04 0x00 0x00 0x00] from 30 and then [0x05 0x00 0x00 0x00] from 28. This would cause byte number 30 to get reset to 0.

I tried reversing the order of the scanfs, and it worked (the output did come out as 4 and 5), so that now, the smaller offset was filled first, and then the latter (larger) offset.

It seemed preposterous that GCC could have messed this up. So I tried MSVC, and the assembly it generated had one marked difference. The variables were placed at offsets -4 and -8 (i.e. they were considered as 4 bytes long, though the comment said 2 bytes). Here's part of the code:

_TEXT   SEGMENT
_x$ = -8    ; size = 2
_y$ = -4    ; size = 2
_main   PROC
    push    ebp
    mov ebp, esp
    sub esp, 8
    xor eax, eax
    mov WORD PTR _x$[ebp], ax
    xor ecx, ecx
    mov WORD PTR _y$[ebp], cx
    lea  edx, DWORD PTR _x$[ebp]
    push    edx
    push    OFFSET $SG2470
    call    _scanf
    add esp, 8
    lea eax, DWORD PTR _y$[ebp]
    push    eax
    push    OFFSET $SG2471
    call    _scanf
    add esp, 8

My question is in two parts:

  • I don't have a personal Linux box at my disposal. Is this a GCC issue, or only a mingw issue?

But, more importantly,

  • Is this a bug at all? How would a compiler figure out if it should place "short"s at 2-byte offsets or 4-byte offsets?
1
  • 1
    "I don't have a personal Linux box at my disposal" - you can fix that by installing VirtualBox on your Windows machine, then installing Linux in a VM. Nov 3, 2012 at 8:25

3 Answers 3

3

To use scanf() on short, you must specify %hd in the format string.

You're provoking overflows because you are lying to scanf(). Turn on the warnings (-Wall at least). You should get complaints from GCC about mismatches. (While you're learning C, use -Wall to catch the silly mistakes you make. When you've been programming in C for more than a quarter century like I have, you'll add some more flags to make sure you still aren't making silly mistakes. And you'll always make sure that the code compiles clean with -Wall.)

GCC 4.7.1 on Mac OS X 10.7.5 says:

ss.c:6:4: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘short int *’ [-Wformat]
ss.c:7:4: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘short int *’ [-Wformat]
2
  • Thanks! Point taken! Just why do the placements of the variables in the program differ for GCC and MSVC?
    – mayur
    Nov 3, 2012 at 9:02
  • The placement of the variables is up to the compiler. One might suggest that MSVC is using more space than GCC; presumably, there is a compensating benefit (faster access). It is slightly unexepected to me that the addresses of &x and &y are 4 bytes apart on MSVC, but it is something that I don't worry about as a C programmer (but would worry about if I was a C compiler writer). Compilers are allowed to implement things differently as long as the behaviour is correct; when accurate code is written, they will both behave correctly on (variants of) this code. Nov 3, 2012 at 15:36
1

Jonathan Leffler's answer explains the problem with scanf. One might wonder how the printf works just fine, then.

The reason printf appears to work is that it's a variadic function, i.e. a function that accepts a variable number of arguments. In the C standard (and therefore in the ABI implemented on Intel platforms), all values of integral types smaller than int (chars, shorts) are passed to variadic functions as ints on the stack and all float values are passed as double. However, this trick doesn't work for scanf, which receives object addresses rather than actual values. Even an error that would be considered "benign" in the context of printf makes scanf overrun the object it's supposed to assign to.

0

Ha! All the digging about the assembly code was an eyewash! A quick Google search for format identifiers yielded a rather hidden one (%hi) to be used for short integers. The problem was with the format specifier in the code and not with the code itself.

So when the scanf was passed the %d, it wrote a 4 byte number to the passed address, and then all the problems illustrated in the question started showing up.

Now, only one question remains. Why did GCC and VC++ differ on the positioning of the variables in the program? Is this just a matter of being pedantic (GCC over VC++) or does this have practical consequences?

3
  • 1
    It's a choice an implementation can make for themselves. GCC uses stack space more efficiently, but MSVC protects you from a certain class of overruns—such as the one you've encountered. It could also be that on some architectures aligning shorts on 4-byte boundaries allowed faster access, and the MSVC arrangement remained. Nov 3, 2012 at 9:07
  • You can use %hi to accept any of 0377, 0xFF, 255 as valid inputs; you can use %hd for decimal input; you can use %hx for hexadecimal; you can use %ho for octal input. The output format %i (equivalent to %d) was added (way back in the C89 standard) to make the formats more consistent between scanf() and printf(). Nov 3, 2012 at 16:50
  • There are any number of reasons that MSVC and GCC might choose to layout the variables differently. One reason might be because when optimizing, MSVC will use more efficient 32-bit accesses to those 16-bit variables when it can. Another reason is 'just because' - you might as well ask why you declared x before y. However, for an interesting example of MSVC choosing a different layout based only on a change in variable name (not type or size), see stackoverflow.com/a/4577565/12711 Nov 3, 2012 at 18:41

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.