Spyke

How do I handle an input thats more than the char size in c?

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?

View original on lemm.ee

Your program will behave correctly: it will read the first 50 characters. There is no undefined behaviour.

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.

3

You reached the end