pjhtml
pjhtml

Reputation: 11

Exception in c scanf_s

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

Upvotes: 0

Views: 357

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

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.

Upvotes: 1

Sofian Moumen
Sofian Moumen

Reputation: 43

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.

Upvotes: 3

Related Questions