error C4996: 'scanf': This function or variable may be unsafe in c programming

180.3k Views Asked by At

I have created a small application to find max number by using user-defined function with parameter. When I run it, it shows this message

Error 1 error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

What do I do to resolve this?

This is my code

#include<stdio.h>

void findtwonumber(void);
void findthreenumber(void);

int main() {
    int n;
    printf("Fine Maximum of two number\n");
    printf("Fine Maximum of three number\n");

    printf("Choose one:");
    scanf("%d", &n);
    if (n == 1)
    {
        findtwonumber();
    }
    else if (n == 2)
    {
        findthreenumber();
    }
    return 0;
}

void findtwonumber(void)
{
    int a, b, max;
    printf("Enter a:");
    scanf("%d", &a);
    printf("Enter b:");
    scanf("%d", &b);
    if (a>b)
        max = a;
    else
        max = b;
    printf("The max is=%d", max);
}

void findthreenumber(void)
{
    int a, b, c, max;
    printf("Enter a:");
    scanf("%d", &a);
    printf("Enter b:");
    scanf("%d", &b);
    printf("Enter c:");
    scanf("%d", &c);
    if (a>b)
        max = a;
    else if (b>c)
        max = b;
    else if (c>a)
        max = c;
    printf("The max is=%d", max);
}
7

There are 7 best solutions below

8
On BEST ANSWER

It sounds like it's just a compiler warning.

Usage of scanf_s prevents possible buffer overflow.
See: http://code.wikia.com/wiki/Scanf_s

Good explanation as to why scanf can be dangerous: Disadvantages of scanf

So as suggested, you can try replacing scanf with scanf_s or disable the compiler warning.

0
On

To disable the compiler warning, add to the very top of your program the following statement: #define _CRT_SECURE_NO_WARNINGS

0
On

Another way is when you create a new project, you don't click to Security Development Lifecycle (SDL) checks:

Or if you are in a project: Right-click your project->Properties->Configuration Properties->C/C++ ->All Options>Sroll your mouse and find SDL checks, you edit it to NO(/sdl-), then Apply, OK

3
On

Another way to suppress the error: Add this line at the top in C/C++ file:

#define _CRT_SECURE_NO_WARNINGS
1
On

#define scanf scan_f

to replace the unsafe version with the safe.

0
On

You can add "_CRT_SECURE_NO_WARNINGS" in Preprocessor Definitions.

Right-click your project->Properties->Configuration Properties->C/C++ ->Preprocessor->Preprocessor Definitions.

enter image description here

1
On

The simple answer is: the scanf() function reads the char/string starting from the first char to the first whitespace.