Why is strdup considered to be evil

Two reasons I can think of:

  1. It’s not strictly ANSI C, but rather POSIX. Consequently, some compilers (e.g. MSVC) discourage use (MSVC prefers _strdup), and technically the C standard could define its own strdup with different semantics since str is a reserved prefix. So, there are some potential portability concerns with its use.
  2. It hides its memory allocation. Most other str functions don’t allocate memory, so users might be misled (as you say) into believing the returned string doesn’t need to be freed.

But, aside from these points, I think that careful use of strdup is justified, as it can reduce code duplication and provides a nice implementation for common idioms (such as strdup("constant string") to get a mutable, returnable copy of a literal string).

Leave a Comment