1

I'm using gcc 4.4.7.

When I run below simple logic(C lang).

Then inputted '1 2'.

 int var1 = 0; 
 int var2 = 0;

 if(!scanf("%ld %ld",&var1, &var2))
 {
    printf("--- ERROR\n");
 }
 else
 {
    printf("--- var1  [%ld] \n", var1);
    printf("--- var2  [%ld] \n", var2);
 }

Result : --- var1 [0] --- var2 [2]

I already know %ld works for long int. What I realy want to know is how does scanf working in detail. This happens when I try to scan 2 or more numbers.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
HyunYoung Go
  • 103
  • 9
  • 2
    `int` is not a `long`. Change declaration to `long int var1`, etc. – Fiddling Bits Dec 18 '19 at 18:21
  • I already know how to figure out this one. I wonder the reason why var2 assigned correctly but var1 does not. – HyunYoung Go Dec 18 '19 at 18:23
  • 2
    This is because you should use `%d` format to match `int`. Also, please don't check the return value from `scanf` with `!` but with the number of conversions expected: `if(scanf("%d %d", &var1, &var2) != 2)` – Weather Vane Dec 18 '19 at 18:24
  • @WeatherVane Could you explain more detail? If just incorrect then, both of them should not be assigned. But it's not. – HyunYoung Go Dec 18 '19 at 18:28
  • @HyunyoungGo that leads to [Undefined Behavior](https://stackoverflow.com/questions/16864552/what-happens-when-i-use-the-wrong-format-specifier), please see my answer, where I merged Weather Vane's and Mark Ronson's comment. – gsamaras Dec 18 '19 at 18:35

1 Answers1

7

The format specifier %ld is for long int (and %lld for long long int).

int should be matched with the %d format specifier. Using a format specifier that does not agree with the variable types leads to Undefined Behavior.

Don't check the return value from scanf with the ! operator but with the number of conversions expected instead, like this:

if(scanf("%d %d", &var1, &var2) != 2)
  printf("--- ERROR\n");

Further Reading
What happens when I use the wrong format specifier?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 6
    The key point left unsaid is that using a format that doesn't agree with the variable types leads to undefined behavior. Trying to make sense of anything after that is worthless. – Mark Ransom Dec 18 '19 at 18:31
  • 1
    @R.. even that is subject to change with different compiler versions. Trying to reason about undefined behavior is a good way to drive yourself crazy. – Mark Ransom Dec 18 '19 at 19:22
  • @MarkRansom: For exploits you just need to know what your target compiled it with. Which is easy if they're using a mainstream binary distro. – R.. GitHub STOP HELPING ICE Dec 18 '19 at 21:12