Home > Mobile >  why should I use scanf_s here instead of scanf?
why should I use scanf_s here instead of scanf?

Time:11-29

A program to swap values:

#include <stdio.h>
#include <conio.h>

void swap(int *a, int *b);

void main()
{
    int a, b;
    printf("Enter two numbers: ");
    scanf_s("%d%d", &a, &b);

    printf("Before swap\n");
    printf("a = %d, b =  %d\n", a, b);
    swap(&a, &b);
    printf("After swap\n");
    printf("a = %d, b = %d", a, b);
}

void swap(int *a, int *b)
{
    printf("Enter the swapped numbers: \n");
    scanf("%d%d", a, b);
}

ERROR

why should I use scanf_s here instead of scanf? Why does this happen?

Thank you for your help.

CodePudding user response:

With scanf you can scan a string :

char buffer[256];
scanf("%s", buffer);

But it can lead to a buffer overflow if the input string is larger than the destination buffer : like strcpy it will copy until it finds a '\0' inside the input. So your compiler is telling you to use scanf_s instead to specify the size of your buffer so it won't write past it :

char buffer[256];
scanf_s("%s", buffer, 256);

But in your case you are just inputing single ints you can use scanf anyway. scanf_s is not a standard function so be careful if your code has to be compile outside visual studio.

More here : Difference between scanf and scanf_s

CodePudding user response:

In the posted code there is no reason to use scanf nor scanf_s in the swap function.

scanf_s is a function introduced by Microsoft as a supposedly safer(1) alternative to scanf that is too often used carelessly by unsuspecting programmers, especially for %s, %[ and %c conversions, leading to security flaws.

scanf_s was standardized as an optional extension with subtly different semantics. Programs using scanf_s are thus not portable.

Microsoft modified their C toolchain to push programmers to use scanf_s, issuing warnings or errors whenever they encounter scanf references. This is the cause for the message shown in the screenshot.

In your program, scanf_s and scanf would behave essentially the same way as the conversion %d%d has the same semantics for both functions, yet scanf_s would detect and handle null pointer arguments for %d (causing the program to exit) whereas scanf would just have undefined behavior (causing the program to exit with a segmentation fault).

The swap function can be written this way:

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

Note also that main should have an int return type.


(1) This subject is quite sensitive as commented by Andrew Henley: scanf_s is a function introduced by Microsoft as a vendor-specific, non-portable, not-any-safer alternative to scanf that results in vendor-lock-in for your code base. An illustration of their internal EEE strategy.

  • Related