It is compiling because your program is syntactically correct. However, it has serious semantic errors which show up as program crash due to segfault. The global array line
is initialized to zero, as any global variable. Since, line
is an array of pointers (not an array of characters which is intended), the zeros are interpreted as NULL
, the null pointer. *line
is same as line[0]
and the string literal "quit"
evaluates to a pointer to its first element. Therefore the while
condition is the same as
while(NULL != "quit") // always true
Next, scanf("%s", *line);
tries to write the input string into the buffer pointed to by line[0]
which is NULL
- a value which is unequal to the address of any memory location. This will result in segfault and cause the program to crash.
There are other mistakes in your code snippet. Let's take them one by one.
char *line[256];
The above statement defines an array line
of 256 pointers to characters, i.e., its
type is char *[256]
. What you need is an array of characters -
char line[256];
You can't compare array in C
. What you can do is compare them element-by-element. For strings, you should use the standard library function strcmp
. Also, please note that the %s
conversion specifier in the format string of scanf
reads a string from stdin
and writes it into the buffer pointed to by the next argument. It puts a terminating null byte at the end but it does not check for buffer overrun if you input a string too large for the buffer to hold. This would lead to undefined behaviour and most likely segfault due to illegal memory access. You should guard against buffer overrun by specifying maximum field width in the format string.
void *mainThread();
The above function declaration means that mainThread
is function which returns a pointer of void *
type and take an unspecified but fixed number and type of arguments because empty parentheses mean no information about the parameter list is provided. You should write void
in the parameter list to mean that the function takes no arguments. Also note that the empty return statement in your function would cause undefined behaviour if the return value of the function is used because you are not returning anything and would be using the garbage value in the return address of the function instead. Assuming that you want to return the string, it should be defined as -
char line[256];
char *mainThread(void) {
while(strcmp(line, "quit") != 0) {
scanf("%255s", line); // -1 for the terminating null byte
printf("%s", line);
}
return line;
}