Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program blocks after input

Tags:

arrays

c

gcc

scanf

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 hand-written implementations of respective algorithms and sorting_prepare_data() is a helper function calling custom-built PRNG on an array. What is the possible cause of blocking? The program has been compiled using GCC, no errors resulted.

like image 380
Erkin Alp Güney Avatar asked Sep 16 '26 12:09

Erkin Alp Güney


1 Answers

I tried you code and manage to reproduce the weird behaviour. If you remove the " " around "%li" it doesn't block anymore.

The problems were the blank spaces because scanf was expecting the input to match the empty space as well.

From the scanf documentation:

All conversions are introduced by the % (percent sign) character. The format string may also contain other characters. White space (such as blanks, tabs, or newlines) in the format string match any amount of white space, including none, in the input. Everything else matches only itself. Scanning stops when an input character does not match such a format character. Scanning also stops when an input conversion cannot be made.

Source : http://www.manpages.info/linux/scanf.3.html

like image 53
Giuseppe Pes Avatar answered Sep 18 '26 06:09

Giuseppe Pes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!