' char* strInput =(char*) malloc(sizeof(char));
        int ch;
        int letNum = 0;
        while((ch = getchar()) != EOF){
                letNum++;
                strInput = (char*)realloc(strInput,letNum*sizeof(char));
                *(strInput + letNum - 1) = ch;
        }
        printf("\n");
        printf("%s\n",strInput);
        free(strInput);`

This is the contents of main in a program I wrote that takes an undefined number of chars and prints the final string. I don’t understand why but it only works if I press ctrl+D twice, and only once if I press enter before.

does anyone get what’s going on? And how would you have written the program?

  • @RangerHere
    link
    2
    edit-2
    1 year ago

    Here are couple suggestions about how to improve your algorithm:

    First of all, you should reduce the number of calls to realloc function. This is because, this function will often need to switch to the kernel space to be able to do the reallocation. I think it is nice to allocate the same size as a single page or multiples of page size from the virtual memory. I think you should allocate 4KB or 2MB of memory at the beginning of the function. Then reallocate multiples of the page size when you need to reallocate memory.

    Second of all, reading the input one character at a time is also time-consuming. Repeatedly calling this function means you will end up going to the kernel space, grabbing a single character from there, then coming back to the user space (I used this as an example, there are many buffers between your application and kernel space). Instead I would suggest you to read 4 kB at the time using read or fread functions.

    If you do not know about files, caching, virtual memory, page sizes, kernel space, user space, and optimization then please disregard everything I said. This will only confuse you now. I know it is a lot of fun to start thinking about optimization when you are learning a new programming language, on the other hand as mathematician and computer scientist Donald Knuth said, premature optimization is the root of all evil.

    I hope this answer helps you.

    • @rastignacOP
      link
      21 year ago

      Thank you, I realize that there’s a whole other aspect I didn’t even consider. I’m new to C and Linux so I’ll follow your advice but it’s making me want to learn more. Thanks again to both you and @adriator for your answers