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.
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.
User contributions licensed under CC BY-SA 3.0