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?

  • buh [any]@hexbear.net
    link
    fedilink
    English
    arrow-up
    7
    ·
    1 year ago

    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