当前位置:网站首页>On the insecurity of using scanf in VS

On the insecurity of using scanf in VS

2022-04-23 14:25:00 KissKernel

# About the vs Use in scanf The problem of insecurity

### First of all scanf Why is it not safe

The first is about memory overflow ,scanf The length of the string you enter will not be detected when using, so there is a risk of memory overflow .

#include<stdio.h>
int main()
{
    
    char arr[6]={
    0};
    scanf("%s",&arr);
    // Assume that the input helloworld There will be the problem of cross-border visits , therefore scanf In this case, it will not be safe .
}

### The second is how to solve scanf The problem of insecurity
There are two ways to solve this problem
1. One is to open vs project Options see the last option attribute
 Insert picture description here

take SDL Check disable
2. In the file .c Insert the following code in the first line of the ;
#define _CRT_SECURE_NO_WARNINGS

Inserting at the beginning of each file is obviously a little cumbersome , So there's another way... Once and for all , Let me introduce it . First find your vs Install path to find this file newc++file.c Copy it to the desktop, and then copy the above code in , Then copy this file back to the original path . Replace the original file .* So why don't you do it here , Because when you change directly in the original path newc++file.c You will be prompted that you do not have permission to change .

### Finally, why scanf_s Security
vs Provided in scanf_s The function needs to specify the number of input characters , So you need to enter an additional qualified number . This ensures that the function will not access beyond the bounds .

#include<stdio.h>
int main()
{
    
    char arr[6];
    scanf_s("%s",&arr,5);// Then there will be no unexpected cross-border visits at this time 
    return 0;
}

There will only be man-made cross-border access, such as you have to enter hello Five characters only define arr[5] So the end of the string \0; It will cross the border because there is no place to place it .
Of course, I still recommend using... In daily programming scanf because scanf_s yes vs If you write it yourself, it will report errors in other compilers , Poor reusability .

I uploaded all the above files in my code cloud , You can see what you need
link

版权声明
本文为[KissKernel]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231412251974.html