How to use scanf_s
This article mainly shows you "how to use scanf_s", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use scanf_s" this article.
Many functions with the "_ s" suffix are designed to make the original function more secure, passing in a size value related to the parameter to avoid referencing elements that do not exist, and sometimes hackers can hack the system by taking advantage of the original insecurity. For example: chard [20]; written as scanf_s ("% s", dPower20); it is correct to have this parameter 20 to improve accuracy.
Introduction to scanf_s
There is no scanf_s () in ANSIC, only scanf (). Scanf () does not check boundaries when reading, so memory access may be out of bounds, such as 5 bytes allocated but 10 bytes read
Charbuf [5] = {'\ 0'}
Scanf ("% s", buf)
If you enter 1234567890, the latter part will be written to another space.
If the above code uses scanf_s, the second line should be changed to scanf_s ("% s", buf,5), indicating that a maximum of 5-1 characters should be read, because buf [4] needs to put'\ 0'.
The last argument to scanf_s is the size of the buffer, which means that a maximum of 1 character is read.
Scanf_s () is available in vc++2005/2008, and scanf_s () is also available in the latest VS2015. When called, a number must be provided to indicate the maximum number of characters to be read.
3. To read a single character, you also need to limit the length: scanf_s ("% c focus% c", & c1Magne1, & c1Magne1); it cannot be written as scanf_s ("% cMagne1% c", & c1pjc2pen1), otherwise the compiler will report an error.
Scanf_s case
Example in MSDN:
/ / crt_scanf_s.c
/ / Thisprogramusesthescanf_sandwscanf_sfunctions
/ / toreadformattedinput.
# include
Intmain (void)
{
Inti,result
Floatfp;charc,s [81]
Wchar_twc,ws [81]
Result=scanf_s ("% d%f%c%C%s%S", & I recorder fpjinghec recorder 1recorder wcreci 1rect sreci 81j wsjiggle 81)
Printf ("Thenumberoffieldsinputis%d\ n", result)
Printf ("Thecontentsare:%d%f%c%C%s%S\ n", iMagne fpdagc recorder wcjime ws)
Result=wscanf_s (L "% d%f%hc%lc%S%ls", & iMagneFpGrade2 wcreachingwcreparent1rewrits81rews81)
Wprintf (L "Thenumberoffieldsinputis%d\ n", result)
Wprintf (L "Thecontentsare:%d%f%C%c%hs%s\ n", iMagne fpjr creco wcjimo ws)
Return0
}
The above is all the contents of this article "how to use scanf_s". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!