Exception in c scanf_s

0

I am trying to write a simple code to input values of an int and a char. Visual studio is throwing an exception

#include<stdio.h>
int main() {

    int i;
    char c;

    printf(" Enter the values");
    scanf_s("%c %d",&c,&i);

    return 0;
}

As i run the program and input values, visual studio is throwing an exception saying : Exception thrown at 0x599C939E (ucrtbased.dll) in main.exe: 0xC0000005: Access violation writing location 0x0032133E

c
visual-studio
exception
asked on Stack Overflow Apr 27, 2019 by pjhtml • edited Apr 28, 2019 by Sofian Moumen

2 Answers

3

You need to specify the sizeof memory you want to allocate for your char.

 scanf_s("%c %d",&c,1,&i);

Won't return any errors. Since the scanf() function is kind of "unsafe", VS forces you to use the scanf_s function, which is a safer option. This way, the user won't be able to trick the input.

answered on Stack Overflow Apr 27, 2019 by Sofian Moumen
1

For format specifiers as c and s there is required to specify the size of the buffer after the corresponding pointer in the list of arguments.

In your case the function call will look like

scanf_s("%c %d",&c, 1, &i);

For format specifier s the size of the buffer also have to take into account the terminating zero.

answered on Stack Overflow Apr 27, 2019 by Vlad from Moscow • edited Apr 27, 2019 by Vlad from Moscow

User contributions licensed under CC BY-SA 3.0