Why is strdup considered to be evil

前端 未结 6 1652
离开以前
离开以前 2020-11-30 09:41

I\'ve seen some posters stating that strdup is evil. Is there a consensus on this? I\'ve used it without any guilty feelings and can see no reason why it is wo

6条回答
  •  青春惊慌失措
    2020-11-30 10:10

    My answer is rather supporting strdup and it is no worse than any other function in C.

    1. POSIX is a standard and strdup is not too difficult to implement if portability becomes an issue.

    2. Whether to free the memory allocated by strdup shouldn't be an issue if anyone taken a little time to read the man page and understand how strdup works. If one doesn't understand how a function works, it's very likely the person is going to mess up something, this is applicable to any function, not just strdup.

    3. In C, memory & most other things are managed by the programmer, so strdup is no worse than forgetting to free malloc'ed memory, failing to null terminate a string, using incorrect format string in scanf (and invoking undefined behaviour), accessing dangling pointer etc.

    (I really wanted to post this as a comment, but couldn't add in a single comment. Hence, posted it as an answer).

提交回复
热议问题