cgets

What value is in the int var when using gets func


I got interest in code golf and I saw the code below from the question:

write a program that gets two one-digit number from stdin separated by space and print the sum of two.

stdin stdout
1 2 3
8 9 17

code (ungolfed)

main(n) {
    gets(&n);
    printf("%d",n%85-43);
}

try it online

I debugged the code and got value of n.

stdin stdout n
1 2 3 3285041

The code outputs the answer, so it must not be undefined value and have to have some meaning.

How come 3285041 got out?


Solution

  • Before we start the explanation, I am going to fix your code to a version that is compatible with the modern standards and remove the deprecated/unsafe functions -

    So -

    #include <stdio.h>
    int main(int n, char* b[])
    {
        fgets((char*)&n, sizeof(n), stdin);
        printf("%d",n%85-43);
    }   
    

    Now that is corrected let us see the explation.

    So fgets (or gets in your case) is usually used to scan strings. How is it scanning integers, that too 2 of them.

    It doesn't, It scans it as a string but in the memory used for an integers. So the bit representation of the integer variable will be made using the bit representation of the string. Here is what value n will get -

    The code relies of the second character being ' ' and the integers being stored such that the least significant byte is stored first. It also assumes that characters use the ASCII representation.

    The ASCII value of 0 is 48 and of a number x (single digit) is 48 + x. The ASCII value of ' ' is 32.

    Assuming the two numbers are x and y, n will be

    (48 + x) + (32 * 256) + ((48 + y) * 65536)
    

    What we are finally using is n % 85 - 43

    If you simplify n % 85 you get x + y + 43.

    The final result thus is x + y which is what is printed by the printf.

    Edit: Here is the simplification of n % 85

    ((48 + x) + (32 * 256) + (65536 * (48 + y))) % 85
    ((48 + x) % 85 + (32 * 256) % 85 + (65536 * (48 + y)) % 85) % 85
    (48 + x + 32 + (3145728 % 85 + 65536y % 85) % 85) % 85
    (80 + x + (48 + 65536y) % 85) %85
    (80 + x + (48 + ((y % 85) * 1) % 85) % 85
    (128 + x + y) % 85
    43 + x + y