일상 메모장

strcat 사용법 및 구현 - C 문자열 처리 본문

C 언어

strcat 사용법 및 구현 - C 문자열 처리

핸드오버 2020. 1. 19. 20:05

사용법

#include <string.h>

char *strcat(char *dest, const char *src);

char *strncat(char *dest, const char *src, size_t n);

정의

strcat() 함수는 src 문자열을 dest 문자열 뒤에 덧붙이고, dest 마지막에 null byte를 삽입합니다.

dest 문자열의 여유 버퍼 크기는 src 문자열을 덧붙이기 충분해야만 합니다.

만약 dest 문자열이 여유 버퍼 크기가 충분치 않다면 dest 버퍼 포인터가

dest 버퍼를 넘어가기때문에 프로그램의 동작을 예측할수 없습니다.

strncat() 함수는 src 문자열의 n 바이트 만큼은 복사에 사용합니다. 

반환 값

dest 문자열의 시작위치를 반환합니다.

 

strcpy() 내부 구현 (strcpy 실제 구현부)

/**
 * strcat - Append one %NUL-terminated string to another
 * @dest: The string to be appended to
 * @src: The string to append to it
 */
char *strcat(char *dest, const char *src)
{
        char *tmp = dest;

        /* dest 문자열의 null byte 위치(문자열 끝)를 찾습니다. */
        while (*dest)
                dest++;
        
        /*
         * dest 문자열끝에서 부터 src 문자열을 계속 복사합니다.
         * src 문자열의 마지막 null byte까지 복사한 후,
         * 루프문을 종료합니다.
         */
        while ((*dest++ = *src++) != '\0')
                ;
        return tmp;
}



/**
 * strncat - Append a length-limited, C-string to another
 * @dest: The string to be appended to
 * @src: The string to append to it
 * @count: The maximum numbers of bytes to copy
 *
 * Note that in contrast to strncpy(), strncat() ensures the result is
 * terminated.
 */
char *strncat(char *dest, const char *src, size_t count)
{
        char *tmp = dest;

        if (count) {
                /* dest 문자열의 null byte 위치(문자열 끝)를 찾습니다. */
                while (*dest)
                        dest++;
                /*
                 * dest 문자열끝에서 부터 src 문자열을 계속 복사합니다.
                 * src 문자를 count 만큼 복사한후,
                 * 마지막에 null byte를 넣습니다.
                 */
                while ((*dest++ = *src++) != 0) {
                        if (--count == 0) {
                                *dest = '\0';
                                break;
                        }
                }
        }
        return tmp;
}

strcat() 함수는 src 문자 한자씩 dest 문자열 끝에서부터 null byte까지 복사합니다.

strncat() 함수도 동일하게 src 문자 한자씩 dest 문자열 끝에서부터 n(count) 만큼 복사한 후 마지막에

null byte를 넣습니다. (만약 n(count) 이전에 src 문자열중 null byte를 만나면 루프를 중단합니다.)

주의 :  내부 소스코드를 보면 알수 있듯이 dest 문자열의 여유 버퍼가 src 문자열을 담을 만큼 없다면,

포인터가 overrun 하여 다른 메모리를 건드리므로 프로그램의 동작을 예측할수 없으므로,

주의해야합니다.

예제

#include <string.h>
#include <stdio.h>

int main()
{
	/* dest의 여유 크기가 src 문자열을 담을수 있어야함!!!! */
	char dest[10] = "abcd";
	char src[] = "efg";

	/* dest 문자열 뒤에 src 문자열을 붙입니다. */
	strcat(dest, src);

	printf("dest : %s\n", dest);

	return 0;
}

결과값은 dest : abcdefg 입니다.