Why is strdup considered to be evil

前端 未结 6 1627
离开以前
离开以前 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:29

    My reason for disliking strdup, which hasn't been mentioned, is that it is resource allocation without a natural pair. Let's try a silly game: I say malloc, you say free. I say open you say close. I say create you say destroy. I say strdup you say ....?

    Actually, the answer to strdup is free of course, and the function would have been better named malloc_and_strcpy to make that clear. But many C programmers don't think of it that way and forgets that strdup requires its opposite or "ending" free to deallocate.

    In my experience, it is very common to find memory leaks in code which calls strdup. It's an odd function which combines strlen, malloc and strcpy.

提交回复
热议问题