Your problem is most likely here:
char *ch=malloc(sizeof("50");
To begin with, you're missing one close parentheses. But assuming that this was a typo in posting the question and not in your actual code, there is a deeper issue.
"50"
inside double quotes is a string literal. When sizeof()
is applied to the string literal, you're going to get the number of characters in the string, including terminating NUL
. So you are only allocating space for three characters in ch
.
When you try to scanf()
the input, you're writing past the end of your three-character buffer ch
. Leave out sizeof()
and simply say:
char* ch = malloc (50);
Also, the scan set %[^\n]
does not skip leading whitespace. Your first scanf()
will stop at the newline, which will remain in the buffer. Subsequent scanf()
calls in your while
loop will encounter that newline character and dutifully stop, as it's excluded from your scan set. So the loop condition
while (strcmp (ch, "exit"))
will never become true, and you'll get an infinite loop. Consume the newline after the scanf()
to avoid this problem:
scanf ("%[^\n]%*c", ch);
The %*c
means "read a character and then discard it." So it will read the \n
that is left in the buffer, and then not save it anywhere. Your next scanf()
will therefore not encounter a \n
at the beginning of the buffer, and your program will work as you intend.