Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

c - 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
", 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...