this post was submitted on 21 Aug 2023
2 points (100.0% liked)

coding

71 readers
1 users here now

founded 1 year ago
 

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?

top 1 comments
sorted by: hot top controversial new old
[–] zerofk@lemm.ee 1 points 1 year ago* (last edited 1 year ago)

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.