Capturing a variable length string from the command-line in C

后端 未结 4 1630
耶瑟儿~
耶瑟儿~ 2021-01-16 06:03

I\'ve looked everywhere for an answer to my question, but I have yet to find a solid answer to my problem.

I\'m currently in the process of writing a program in C, s

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-16 06:29

    You dont need do any realloc, just add 1 byte more than the maximum command length for \0 and forget \n because you wont get a \n always the user type enter. If the user input exceed the length then your string will be truncated without the \n. So your condition after fgets is not correct and based in a wrong assumption.

    something like:

       int buffer_size = MAX_COMMAND_LENGTH + 1;
    

    About memory allocation: you should use stack instead heap avoiding malloc/free in this case. So your code will be simpler and less error prone:

        char command[buffer_size];
        ...
        // free(command) <-- you dont need this anymore
    

    Note that your command will be freed after function return. So if you will process it into get_command its ok but if you want return it to caller you shall receive a buffer from caller.

提交回复
热议问题