strdup() — 스트링 복제

형식

#include <string.h>
char *strdup(const char *string);
참고: strdup 함수는 C++ 프로그램에서 사용 가능합니다. 프로그램이 __cplusplus__strings__ 매크로를 정의할 때만 C에서 사용 가능합니다.

언어 레벨

XPG4, 확장

스레드세이프

설명

strdupmalloc을 호출하여 string의 사본에 대한 기억장치 공간을 예약합니다. 이 함수에 대한 스트링 인수는 스트링 끝을 나타내는 널 문자(\0)를 포함한다고 예상됩니다. strdup에 대한 호출로 예약된 기억장치를 해제해야 합니다.

리턴값

strdup은 복사된 스트링을 포함하는 기억장치 공간에 대한 포인터를 리턴합니다. 기억장치를 예약할 수 없으면 strdupNULL을 리턴합니다.

이 예는 strdup을 사용하여 스트링을 복제하고 사본을 인쇄합니다.
#include <stdio.h>
#include <string.h>
int main(void)
{
   char *string = "this is a copy";
   char *newstr;
   /* Make newstr point to a duplicate of string                              */
   if ((newstr = strdup(string)) != NULL)
      printf("The new string is: %s\n", newstr);
   return 0;
}
출력은 다음과 같아야 합니다.
      The new string is: this is a copy