I get this error 0xC0000005: Access violation writing location 0x0086B000

3

I tired the same code on https://repl.it/languages/c and i get no errors but when i paste the same code on Visual Studio 2017 I get this error regarding:

#include <stdio.h>
#include <string.h>
char input[100];
int calc();
int main() {
    printf("Type \"help\" or enter a mathematical expression\n");
    calc();
}
int calc() {
    printf("Calc:\\> ");
    scanf_s("%s", input);
    if (strcmp(input, "help") == 0) {
        printf("Help is on the way\n");
    }
    else {
        printf("Answer:\\> %s\n", input);
    }
    calc();
    return 0;
}

But I get this error when i run it:

Exception thrown at 0x50FFD4EC (ucrtbased.dll) in Project.exe: 0xC0000005: Access violation writing location 0x0086B000.
c
asked on Stack Overflow May 31, 2019 by Bipin • edited May 31, 2019 by Bipin

1 Answer

4

Problem 1:

You are calling calc() recursively without a base case. This means that you will inevitably cause the stack to overflow when you call that function.

Solution: Remove the recursive call to calc() in calc().

Problem 2:

scanf_s requires that the string argument satisfying a %s format specifier comes immediately before an integer variable giving the length of the buffer. See its documentation on MSDN.

Solution: pass the length of the string as well:

scanf_s("%s", input, 100);

Side note: checking the return value of scanf-family functions is usually a good idea.

answered on Stack Overflow May 31, 2019 by Govind Parmar

User contributions licensed under CC BY-SA 3.0