Program blocks after input
This code blocks immediately after scanf()
:
int main(int argc, char *argv[]) {
puts("Algorithms test kit");
long input_size;
FILE *output=fopen("output.txt","w+");
do {
printf("Enter sample size(0 goes on to next test) > ");
scanf (" %li ",&input_size);
printf ("#");
if (input_size==0) break;
int64_t *data=sorting_prepare_data(input_size);
int64_t *bsort_copy=calloc(input_size,8);
int64_t *qsort_copy=calloc(input_size,8);
memcpy(bsort_copy,data,input_size*8);
bubblesort(bsort_copy,input_size);
memcpy(qsort_copy,data,input_size*8);
quicksort(qsort_copy,input_size);
for (size_t i=0;i<input_size;i++) {
fprintf(output,"%lld\t%lld\t%lld\n",data[i],bsort_copy[i],qsort_copy[i]);
printf(".");
}
free(data); free(bsort_copy); free(qsort_copy);
} while (input_size);
return;
}
Where bubblesort()
and quicksort()
are handwritten implementations of the corresponding algorithms, and sorting_prepare_data()
is a helper function that calls a custom PRNG for the array. What is the possible reason for blocking? The program was compiled using GCC and there were no errors.
source to share
I tried the code and was able to reproduce the strange behavior. If you remove " "
around "%li"
, it is no longer blocked.
The problem was whitespace, because I scanf
expected the input to also match whitespace.
From the documentation scanf
:
All conversions are entered with a% symbol (percent sign). The format string can also contain other characters. White space (such as spaces, tabs, or newlines) in the format string matches any number of spaces, including none, in the input. Everything else matches only itself. Scanning stops when the input character does not match such a format character. Scanning also stops when conversion of the input cannot be done .
source to share