본문 바로가기
Code/C

[C언어] 내장함수 비교 - strcpy, strncpy, strlcpy

by 코드포휴먼 2020. 10. 1.

C언어의 <string.h>에 있는 str 관련 함수들은 공부해도 항상 헷갈린다.

필요한 순간마다 블로깅하여 확실하게 정리한다.

man 가이드의 원문을 활용했다.

 

cpy

strcpy

PROTOTYPE #include <string.h>
char *strcpy(char *dst, const char *src);
DESCRIPTION - The strcpy() function copies the string src to dst (including the terminating `\0' character.)
RETURN dst
SECURITY CONSIDERATIONS - The strcpy() function copies the string src to dst (including the terminating `\0' character.) 
The strcpy() function is easily misused in a manner which enables malicious users to arbitrarily change a running program's functionality through a buffer overflow attack.

 

 

strncpy

PROTOTYPE #include <string.h>
char *strncpy(char *dst, const char *src, size_t len);
DESCRIPTION - The strncpy() function copies at the most len characters from src into dst. If src is less than len characters long, the remainder of dst is filled with `\0' characters. Otherwise, dst is not terminated.
RETURN dst
SECURITY CONSIDERATIONS - strncpy() does not guarantee to NUL terminate the string itself.

 

사용예시

// The following sets chararray to ``abc\0\0\0'':
 char chararray[6];
(void)strncpy(chararray, "abc", sizeof(chararray));


// The following sets chararray to ``abcdef'':
// Note that it does not NUL terminate chararray because the length of the source string is greater than or equal to then length argument.
char chararray[6];
(void)strncpy(chararray, "abcdefgh", sizeof(chararray));


// The following copies as many characters from input to buf as will fit and NUL terminates the result.
// Because strncpy() does not guarantee to NUL terminate the string itself, this must be done explicitly.
// This could be better achieved using strlcpy().
char buf[1024];
(void)strncpy(buf, input, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';

두 번째 예시의 경우 src 길이가 dst의 길이 보다 같거나 크기 때문에 문자열 dst에 NUL 문자가 삽입되지 않았다.

이처럼 strncpy는 NUL 문자를 보장하지 않는다.

따라서 strncpy를 사용하여 문자열을 복사할 시 세 번째 예시처럼 작성하면 좋다.

dst의 길이보다 1 작은 길이를 세번째 매개변수로 넘기면 추후에 마지막 인덱스에 직접 NUL 문자를 넣어주면 된다.

세 번째 예시의 행위는 strncpy보다 strlcpy에서 지원해준다.

 

 

strlcpy

PROTOTYPE #include <string.h>
size_t strlcpy(char *restrict dst, const char *restrict src, size_t dstsize);
DESCRIPTION - The strlcpy() function copies and concatenate strings with the same input parameters and output result as snprintf(3).
- It is designed to be safer, more consistent, and less error prone replacements 
for the easilymisused functions strncpy(3).   
- strlcpy() takes the full size of the destination buffer and copies up to dstsize - 1 characters from the string src to dst, NUL-terminating the result if dstsize is not 0.

RETURN the length of src
: the total length of the string they tried to create.
SECURITY CONSIDERATIONS - strlcpy() guarantees NUL-termination if there is room.   
Note that room for the NUL should be included in dstsize. 

 

 

strncpy와 strlcpy 비교

PROTOTYPE char *strncpy(char *dst, const char *src, size_t len); size_t strlcpy(char *restrict dst, const char *restrict src, size_t dstsize);
NAME copy strings size-bounded string copying and concatenation
RETURN dst the length of src
NUL Assurance strncpy() does not guarantee to NUL terminate. strlcpy() guarantees NUL-termination.
src size < copying size

- The output string will be truncated as much as length of src.

- Fill the remaining number with NUL characters. (Inefficient)

- Add only one NUL character and end the function immediately. (Efficient)

dst size < copying size overflow error

 


추가로 보면 좋을 블로그 글

jhnyang.tistory.com/171

댓글