The strcpy and strncpy functions are part of the C standard library and work with existing memory. That is, you must provide a memory in which functions copy string data, and as a result, you must have your own ways of knowing how much memory you need.
Depending on the constant, strdup is a Posix function and performs dynamic memory allocation for you. It returns a pointer to the newly allocated memory to which it copied the string. But you are now responsible for this memory and should ultimately free it.
This makes strdup one of the "hidden malloc " convenience functions, and this is apparently also why it is not part of the standard library. As long as you use the standard library, you know what you should call free for each malloc / calloc . But functions like strdup introduce hidden malloc , and you should treat it like malloc does for memory management. (Other such hidden selection features are GCC abi::__cxa_demangle() .) Beware!
Kerrek SB Dec 24 2018-12-12T00: 00Z
source share