简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM