Do You Coding?

[library] strdup ๊ตฌํ˜„ํ•˜๊ธฐ ๋ณธ๋ฌธ

CS & Engineering/C

[library] strdup ๊ตฌํ˜„ํ•˜๊ธฐ

๐Ÿ“Œ ๋งค๋‰ด์–ผ (Linux)

๋”๋ณด๊ธฐ

NAME
       strdup - duplicate a string
: ๋ฌธ์ž์—ด ๋ณต์ œํ•˜๊ธฐ


SYNOPSIS
       #include <string.h>
       char *strdup(const char *s);

DESCRIPTION
       The  strdup() function returns a pointer to a new string which is a duโ€
       plicate of the string s.  Memory for the new string  is  obtained  with
       malloc(3), and can be freed with free(3).
: strdup ํ•จ์ˆ˜๋Š” ๋ฌธ์ž์—ด์˜ ๋ณต์ œ์ธ ์ƒˆ ๋ฌธ์ž์—ด์— ํฌ์ธํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ์ƒˆ ๋ฌธ์ž์—ด์— ๋Œ€ํ•œ ๋ฉ”๋ชจ๋ฆฌ๋Š”

malloc์„ ์‚ฌ์šฉํ•˜๊ณ , free๋กœ ํ•ด์ œํ•  ์ˆ˜ ์žˆ๋‹ค.


RETURN VALUE
       On  success,  the strdup() function returns a pointer to the duplicated
       string.  It returns NULL if insufficient memory was available, with erโ€
       rno set to indicate the cause of the error.
: ์„ฑ๊ณต ์‹œ, strdup ํ•จ์ˆ˜๋Š” ๋ณต์ œ๋œ ๋ฌธ์ž์—ด์— ๋Œ€ํ•œ ํฌ์ธํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ , ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ์ถฉ๋ถ„ํ•˜์ง€ ์•Š์œผ๋ฉด NULL์„

๋ฐ˜ํ™˜ํ•˜๋ฉฐ ์˜ค๋ฅ˜์˜ ์›์ธ์„ ๋‚˜ํƒ€๋‚ด๋Š” ์—๋Ÿฌ ์ˆซ์ž๋ฅผ ์„ค์ •ํ•œ๋‹ค.

 

๐Ÿ“Œ ์ž‘์„ฑ ์ฝ”๋“œ

char	*do_strdup(const char *s)
{
	char	*dup;
	size_t	s_len;
	size_t	i;

	s_len = do_strlen(s);
	i = 0;
	dup = (char *)malloc(sizeof(char) * (s_len + 1));
	if (dup == NULL)
		return (NULL);
	while (s[i] != '\0')
	{
		dup[i] = s[i];
		i ++;
	}
	dup[i] = '\0';
	return (dup);
}

 

๐Ÿ“Œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ

strdup ํ•จ์ˆ˜๋Š” ์ธ์ž๋กœ ๋ฐ›์€ s ๋ฌธ์ž์—ด์„ ๋ณต์‚ฌํ•ด ์ƒˆ๋กœ์šด ๋ฌธ์ž์—ด์— ๋„ฃ์–ด์ฃผ๊ณ  returnํ•ด์ฃผ๋Š” ๋™์ž‘์„ ํ•œ๋‹ค.

์šฐ์„  ๋ฐ›์•„์˜จ s ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ ๊ตฌํ•˜์—ฌ ํ•ด๋‹น ๊ธธ์ด๋งŒํผ malloc์œผ๋กœ ๋™์ ํ• ๋‹น์„ ํ•ด์ค€๋‹ค. (๋ฌธ์ž์—ด ๋งˆ์ง€๋ง‰์— null ๋„ฃ์–ด์ฃผ๋Š”

๊ฒƒ์„ ๊ณ ๋ คํ•ด์„œ s_len + 1 ๋งŒํผ ํ• ๋‹นํ•ด์ฃผ์–ด์•ผํ•˜๋ฉฐ, ์ž๋ฃŒํ˜• ๊ธธ์ด์ธ sizeof(char) ๋„ ์ผ๋ฐ˜์ ์œผ๋กœ ์ ์–ด์ค˜์•ผํ•˜๋‚˜ 1์ด๋ฏ€๋กœ ์ƒ๋žต)

 

๊ทธ ์ดํ›„, ํ• ๋‹น์ด ์•ˆ๋˜์–ด dup์ด NULL์ธ ๊ฒฝ์šฐ์— ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๋กœ NULL์„ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ํ–ˆ๊ณ ,

๋ฐ˜๋ณต๋ฌธ์„ NULL์„ ๋งŒ๋‚  ๋•Œ๊นŒ์ง€๋กœ ์„ค์ •ํ•˜์—ฌ s ๋ฌธ์ž์—ด์„ ํ• ๋‹นํ•ด๋‘” dup์— ํ•˜๋‚˜์”ฉ ๋„ฃ์–ด์ฃผ๋„๋ก ๋ฐ˜๋ณตํ–ˆ๋‹ค.

๊ทธ ํ›„ ๋ฌธ์ž์—ด ๋งˆ์ง€๋ง‰ ๋ถ€๋ถ„์— NULL(\0)์„ ๋„ฃ์–ด์ฃผ๋ฉด์„œ ๋งˆ๋ฌด๋ฆฌํ•ด์ฃผ๊ณ , ํ•ด๋‹น dup์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด์„œ ๋™์ž‘์„ ์ข…๋ฃŒํ•œ๋‹ค.

 

์ด ํ•จ์ˆ˜๊ฐ€ ํ™œ์šฉ์„ฑ์ด ์ •๋ง ํฌ๋‹ค๋Š” ์ ์„ ์ดํ›„ ๊ณผ์ œ์—์„œ ๋งŽ์ด ๋А๋ผ๊ณ  ์žˆ๋‹ค. const๋กœ ๋งŒ๋“ค์–ด์ ธ ์ˆ˜์ •ํ•  ์ˆ˜ ์—†๋Š” ๋ฌธ์ž์—ด ๋“ฑ์„

์ƒˆ ๋ฐฐ์—ด์— ๋ณต์‚ฌํ•ด์„œ ์ž์ฃผ ์‚ฌ์šฉํ•˜๊ฒŒ ๋˜๋Š” ๋ถ€๋ถ„์ด ๋งŽ์•˜๊ณ , strdup์ด ์—ฌ๊ธฐ์„œ ์ž์ฃผ ์ž˜ ์“ฐ์ด๋Š” ๊ฒƒ ๊ฐ™๋‹ค.