cross-posted from: https://lemm.ee/post/4890334

cross-posted from: https://lemm.ee/post/4890282

let’s say I have this code

` #include #include char name[50]; int main(){ fgets(name,50,stdin); name[strcspn(name, “\n”)] = ‘\0’; printf(“hi %s”, name); }

` and I decide my name is “ewroiugheqripougheqpiurghperiugheqrpiughqerpuigheqrpiugherpiugheqrpiughqerpioghqe4r”, my program will throw some unexpected behavior. How would I mitigate this?

  • frankfurt_schoolgirl [she/her]
    link
    fedilink
    English
    1311 months ago

    If you want to accept a user input of any length, you have to read the input piece by piece and allocate a new buffer if the original becomes full. Basic steps would be:

    1. Use malloc to make a char * buffer
    2. Read one character at a time in a while loop, keep track of your position in the buffer
    3. If you get an EOF character, add a \0 to your buffer and break the loop. You’re done!
    4. If the position is greater than the length, allocate a new buffer that has twice the length. Use memcpy to copy the stuff from the old buffer to the new one. Use free to get rid of the old buffer.

    This will work until you fill the entire memory of your computer. You should probably set a max length and print an error if it is reached.

    • buh [any]
      link
      fedilink
      English
      711 months ago

      this is the right answer for the question, the only thing I would suggest is in step 4, to use realloc instead of doing malloc/memcpy/free cycles, since realloc does all that and will simply extend the allocated space so it can skip the memcpy and free steps if possible, which is a little faster

    • xigoi
      link
      211 months ago
      1. Realize that you’ll have to do something like this every time you want to work with a string of unknown size
      2. Cry
      3. Use a different language