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?
Your program will behave correctly: it will read the first 50 characters. There is no undefined behaviour. (Small correction: there is undefined behaviour if no newline is found, but this is easily fixed by then setting the last char to null.)
That said, if you want to handle arbitrary length names, you can do dynamic memory allocation. You keep reading until you find the end of the name, say in chunks of 50 chars, and allocate a new array when needed. Once everything has been read you know the full length and can consternatie.
It is important to note this has many implications for performance, security, memory consumption, etc.