strcpy vs strdup

前端 未结 5 1938
抹茶落季
抹茶落季 2020-11-28 02:48

I read that strcpy is for copying a string, and strdup returns a pointer to a new string to duplicate the string.

Could you please explain

5条回答
  •  不知归路
    2020-11-28 03:13

    The functions strcpy and strncpy are part of the C standard library and operate on existing memory. That is, you must provide the memory into which the functions copy the string data, and as a corollary, you must have your own means of finding out how much memory you need.

    By constrast, strdup is a Posix function, and it performs dynamic memory allocation for you. It returns a pointer to newly allocated memory into which it has copied the string. But you are now responsible for this memory and must eventually free it.

    That makes strdup one of the "hidden malloc" convenience functions, and that's presumably also why it is not part of the standard library. As long as you use the standard library, you know that you must call one free for every malloc/calloc. But functions such as strdup introduce a hidden malloc, and you must treat it the same as a malloc for the purpose of memory management. (Another such hidden allocation functions is GCC's abi::__cxa_demangle().) Beware!

提交回复
热议问题