this post was submitted on 21 Aug 2023
26 points (100.0% liked)
Programming
17398 readers
159 users here now
Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!
Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.
Hope you enjoy the instance!
Rules
Rules
- Follow the programming.dev instance rules
- Keep content related to programming in some way
- If you're posting long videos try to add in some form of tldr for those who don't want to watch videos
Wormhole
Follow the wormhole through a path of communities [email protected]
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
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:
malloc
to make achar *
buffer\0
to your buffer and break the loop. You're done!memcpy
to copy the stuff from the old buffer to the new one. Usefree
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.
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
Didn't know about that one, thanks!