I've heard how scanf can pose security risks.
What would be the correct and safe way to use it, so that those risks would be avoided?
I've heard how scanf can pose security risks.
What would be the correct and safe way to use it, so that those risks would be avoided?
It is generally a better idea to use fgets + sscanf. But one place to be especially careful is with string input -- always specify a maximum length. I believe there are a few other general "avoid" directives, but I can't think of them at the moment. And make sure that you've got a compiler or linter that can help you not screw up directives with their corresponding arguments.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
Not use it at all would be my suggestion.
The only truly safe operation is %c, which you may as well use fgetc()
%s can limit the length with say "%10s", but there's no easy way to relate that to the size of the buffer (like you can with fgets). In addition, the 10 represents the number of characters to be stored (not the length of the buffer).
All the numeric conversions fail to detect numeric overflow or underflow.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I'm interested in %d and %f.
Using fgets and sscanf seems a little tedious.
Can anyone give an example of how would I read a number from stdin securely (with use of scanf, fgets, sscanf or any other function) ?
this would be the simplest that u can use to get an integer valueUsing fgets and sscanf seems a little tedious.
but Daves solution would be best for the this.Code:fgets(str, sizeof str, stdin) sscanf(str,,"%d",&num)'
ssharish2005