Search code examples
cscanfstdio

What will happen if '&' is not put in a 'scanf' statement?


I had gone to an interview in which I was asked the question:

What do you think about the following?

int i;
scanf ("%d", i);
printf ("i: %d\n", i);

I responded:

  • The program will compile successfully.
  • It will print the number incorrectly but it will run till the end without crashing

The response that I made was wrong. I was overwhelmed.

After that they dismissed me:

The program would crash in some cases and lead to an core dump.

I could not understand why the program would crash? Could anyone explain me the reason? Any help appreciated.


Solution

  • When a variable is defined, the compiler allocates memory for that variable.

    int i;  // The compiler will allocate sizeof(int) bytes for i
    

    i defined above is not initialized and have indeterminate value.

    To write data to that memory location allocated for i, you need to specify the address of the variable. The statement

    scanf("%d", &i);
    

    will write an int data by the user to the memory location allocated for i.

    If & is not placed before i, then scanf will try to write the input data to the memory location i instead of &i. Since i contains indeterminate value, there are some possibilities that it may contain a value equivalent to the value of a memory address or it may contain a value which is out of range of memory address.

    In either case, the program may behave erratically and will lead to undefined behavior. In that case anything could happen.