-1

I'm studying C language, I ran these codes in Microsoft Visual Studio, but I got an access violation exception, Could you please help me find out the reason?

#include <stdio.h>

int main() {

    char name[10];

    printf("Enter your name\n");

    scanf_s("%s", name);

    printf("Welcome %s\n", name);

    return 0;
}

I've looked for numerous solutions to this, however some are no effective. I tried removing the & from the name, but that didn't help.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Alson K
  • 1
  • 1
  • The input I tried to type was John – Alson K Feb 19 '23 at 09:16
  • 2
    What's the rationale behind using ```scanf_s``` instead of `scanf` or `fgets`? One would have thought that these seemingly safe functions take an extra argument. But if they don't, how else do they prevent buffer overflows? – Harith Feb 19 '23 at 09:18

1 Answers1

2

You need to provide the length of name to scanf_s too:

scanf_s("%s", name, (unsigned)sizeof name);

Without the lenght, the program will have undefined behavior and may therefore crash

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • I don't understand how iinks with an argument mismatch:(( – Martin James Feb 19 '23 at 14:42
  • @MartinJames The function is variadic so the missing argument will slip through linking. If you turn up the warning level of your compiler I assume that the compiler will warn about it though. If compiled as you wrote it, the function will pick one `unsigned` from the stack. Since you didn't put one there, it will corrupt the stack, and then anything can happen. You must always supply the right number and types of arguments to all function or you'll have undefined behavior. – Ted Lyngmo Feb 21 '23 at 22:33