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?
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.