Why is strdup considered to be evil

前端 未结 6 1653
离开以前
离开以前 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条回答
  •  猫巷女王i
    2020-11-30 10:29

    I haven't really heard strdup described as evil, but some possible reasons some people dislike it:

    1. It's not standard C (but is in POSIX). However I find this reason silly because it's nearly a one-line function to add on systems that lack it.
    2. Blindly duplicating strings all over the place rather than using them in-place when possible wastes time and memory and introduces failure cases into code that might otherwise be failure-free.
    3. When you do need a copy of a string, it's likely you actually need more space to modify or build on it, and strdup does not give you that.

提交回复
热议问题