C4996 c ошибка scanf

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);
}

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);
}

The error «C4996: ‘scanf’: This function or variable may be unsafe in c programming» is a warning message generated by the Microsoft Visual C++ compiler, indicating that the use of the ‘scanf’ function may result in security vulnerabilities. This warning message is part of the compiler’s security features, which aim to prevent potential security breaches by flagging potentially unsafe functions.

Method 1: Use fgets() and sscanf() instead of scanf()

To fix error C4996: ‘scanf’: This function or variable may be unsafe in c programming, you can use fgets() and sscanf() instead of scanf(). Here’s how to do it in a few simple steps:

  1. Use fgets() to read input from the user. This function reads a line of text from the input stream and stores it in a buffer.
char input[100];
fgets(input, sizeof(input), stdin);
  1. Use sscanf() to parse the input. This function reads formatted input from a string and stores the values in variables.
int num;
sscanf(input, "%d", &num);
  1. Use the variables to perform any necessary calculations or operations.
int result = num * 2;
printf("The result is: %d\n", result);

Here’s the complete code example:

#include <stdio.h>

int main() {
  char input[100];
  int num;

  printf("Enter a number: ");
  fgets(input, sizeof(input), stdin);
  sscanf(input, "%d", &num);

  int result = num * 2;
  printf("The result is: %d\n", result);

  return 0;
}

This code reads a number from the user, doubles it, and prints the result. By using fgets() and sscanf() instead of scanf(), we avoid the potential security issues associated with scanf().

Method 2: Use the «_CRT_SECURE_NO_WARNINGS» preprocessor directive

To fix the error C4996: ‘scanf’: This function or variable may be unsafe in c programming, you can use the «_CRT_SECURE_NO_WARNINGS» preprocessor directive. This directive tells the compiler to ignore the warning and allows you to use the unsafe functions like scanf. Here are the steps to use this directive:

  1. Open your Visual Studio project.

  2. Right-click on the project in the Solution Explorer and select Properties.

  3. In the Properties window, click on the C/C++ tab and select Preprocessor from the left-hand menu.

  4. In the Preprocessor Definitions field, add «_CRT_SECURE_NO_WARNINGS» (without quotes) and click OK.

Here is an example code that uses scanf with the «_CRT_SECURE_NO_WARNINGS» directive:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("You entered: %d", num);
    return 0;
}

In this example, we define the «_CRT_SECURE_NO_WARNINGS» directive before including the stdio.h header file. This tells the compiler to ignore the warning for the scanf function.

Another example code that uses scanf with the «_CRT_SECURE_NO_WARNINGS» directive and checks for errors:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main() {
    int num;
    printf("Enter a number: ");
    if (scanf("%d", &num) != 1) {
        printf("Error: Invalid input.");
        return 1;
    }
    printf("You entered: %d", num);
    return 0;
}

In this example, we use the scanf function to read an integer from the user. We check if the return value of scanf is 1, which indicates that one integer was successfully read. If the return value is not 1, we print an error message and exit the program.

Using the «_CRT_SECURE_NO_WARNINGS» directive allows you to use the scanf function without warnings, but you should always validate user input to prevent errors and vulnerabilities in your code.

Method 3: Use the secure version of scanf(), such as scanf_s()

To fix the error C4996: ‘scanf’: This function or variable may be unsafe in C programming, you can use the secure version of scanf(), such as scanf_s(). Here’s how to do it:

  1. Include the header file «stdio.h» and «stdlib.h» in your program.
#include <stdio.h>
#include <stdlib.h>
  1. Replace scanf with scanf_s and add the size of the input buffer as the second parameter.
char str[50];
scanf_s("%s", str, 50);
  1. If you want to read in a specific number of characters, you can use the format specifier «%Ns», where N is the maximum number of characters to read.
char str[50];
scanf_s("%49s", str, 50);
  1. If you want to read in a string with spaces, you can use the format specifier «%[^\n]s».
char str[50];
scanf_s("%49[^\n]s", str, 50);
  1. If you want to read in an integer, you can use the format specifier «%d».
int num;
scanf_s("%d", &num);
  1. If you want to read in a float, you can use the format specifier «%f».
float num;
scanf_s("%f", &num);
  1. If you want to read in a double, you can use the format specifier «%lf».
double num;
scanf_s("%lf", &num);

That’s it! By using scanf_s() instead of scanf, you can fix the error C4996: ‘scanf’: This function or variable may be unsafe in C programming.

Compile the C language project in VS, if the scanf function is used, the following error will be prompted when compiling:

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.

The reason is that Visual C++ uses more secure run-time library routines. The new Security CRT functions (that is, those with the “_s” suffix), please see

“Security Enhanced Version of CRT Function”

The solution to this problem is given below:

Method 1 : Replace the original old functions with new Security CRT functions.

Method 2 : Use the following methods to block this warning:

  1. Define the following macros in the precompiled header file stdafx.h (note: it must be before including any header files):
#define _CRT_SECURE_NO_DEPRECATE
  1. Or statement
#pragma warning(disable:4996)
  1. Change the preprocessing definition:

    Project -> Properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definition, add:

_CRT_SECURE_NO_DEPRECATE

Method three : Method two does not use the more secure CRT function, which is obviously not a good method worth recommending, but we don’t want to change the function names one by one. Here is an easier method:

Define the following macros in the precompiled header file stdafx.h (also before including any header files):

#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1

When linking, it will automatically replace the old functions with Security CRT functions.

Note: Although this method uses a new function, it cannot eliminate the warning. You have to use method two (-_-) at the same time. In other words, the following two sentences should actually be added to the precompiled header file stdafx.h:

#define _CRT_SECURE_NO_DEPRECATE

#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1

Explanation of the cause of the error:

This kind of warning from Microsoft is mainly because of the functions of the C library. Many functions do not perform parameter detection (including out-of-bounds). Microsoft is worried that using these will cause memory exceptions, so it rewrites the functions of the same function. The function of has carried out parameter detection, and it is safer and more convenient to use these new functions. You don’t need to memorize these rewritten functions specifically, because the compiler will tell you the corresponding safe function when it gives a warning for each function. You can get it by checking the warning message. You can also check MSDN for details when you use it.

Similar Posts:

When using the ‘scanf’ function in C programming, you may encounter the error “C4996: ‘scanf’: This function or variable may be unsafe”. This error occurs because ‘scanf’ is identified as an unsafe function that can lead to buffer overflow vulnerabilities.

To fix this error, you can use the ‘scanf_s’ function instead of ‘scanf’. The ‘scanf_s’ function is a secure version of ‘scanf’ that requires you to specify the buffer size of the input. This helps prevent buffer overflow vulnerabilities.

Here is an example of how to use ‘scanf_s’:

#include <stdio.h>

int main() {
   char name[20];
   int age;

   printf("Enter your name: ");
   scanf_s("%s", name, 20);

   printf("Enter your age: ");
   scanf_s("%d", &age);

   printf("Your name is %s and you are %d years old\n", name, age);

   return 0;
}

In this example, ‘scanf_s’ is used to read in a string and an integer. The ‘name’ variable is an array of characters with a size of 20, which is specified in the second argument of the ‘scanf_s’ function. The ‘age’ variable is an integer, so we use the ‘&’ operator to get the memory address of the variable.

By using ‘scanf_s’ instead of ‘scanf’, we can ensure that there are no buffer overflow vulnerabilities in our code.

In addition to using ‘scanf_s’, there are other best practices you can follow to avoid buffer overflow vulnerabilities. These include:

  • Always validating user input and checking that it does not exceed the maximum buffer size
  • Using ‘fgets’ instead of ‘gets’ to read in strings
  • Using ‘strncpy’ instead of ‘strcpy’ to copy strings

By following these best practices, you can avoid buffer overflow vulnerabilities and ensure that your C programs are secure.

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • C7303 ошибка kyocera
  • C4996 c ошибка fopen
  • C7001 kyocera ошибка
  • C7301 kyocera 5501 ошибка
  • C7104 ошибка kyocera

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: