3

I set a char array of size of 10 and want to check the real size of the input permitted.

I tested

123456789; 1234567890; 123456789123456789

Interestingly, all of them passed and got the right output which are

123456789; 1234567890; 123456789123456789

It confused me a lot because I thought the last two are wrong input.

Does that make sense or is it a compiler difference?

This is the code

#include <stdio.h>
main()    
{    
char input[10];    
scanf("%s", input);    
printf(input);    
}  '  

2 Answers 2

6

The scanf() with format specifier %s scans the input until a space is encountered. In your case, what you are seeing is undefined behavior. Your array can hold 10 chars, but you are writing out of its boundaries.

While you are getting an expected answer now, this is not always guarnateed and may instead cause a crash.

It is advisable to use a function such as fgets() takes care of buffer overflow.

Sign up to request clarification or add additional context in comments.

1 Comment

With input that is long enough, you are guaranteed to cause a crash. The reason is that with increasing input, the individual bytes get written to higher memory addresses. In most machines today, the stack grows downwards. Therefore your buffer overrun will destroy the stack above main(), and when main() terminates, all sort of hell will happen. If you have a stack protector, it will detect it; otherwise, you'll likely create a segfault. But even worse tthings could happen. This a preferred route for malware attacks.
0

You can use

scanf("%9s", input);    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.