string.h 函数 - strncpy 和 strncat 奇怪的行为

string.h functions - strncpy and strncat strange behaviour

我正在测试一些 string.h 函数并在使用函数 strncpystrncat 时发现一个奇怪的行为。

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

int main()
{
    char name1[30], name2[30], name3[30], name4[30], name5[30];
    char *res;
        
    printf("First name: ");
    scanf("%[^\n]", name1);

    setbuf(stdin, NULL);
    printf("\nSecond name: ");
    scanf("%[^\n]", name2);
    
    strcpy(name3, name2);
    printf("\nname3: %s", name3);
    
    strncpy(name4, name3, 5);
    printf("\nname4: %s", name4);

    //printf("\nSize of first name: %zu", strlen(nome1)); //zu para size_t
    //printf("\nTamanho do segundo nome: %d", (int) strlen(nome2));

    strncpy(name5, name1, 3);
    printf("\nname1: %s", name1);
    printf("\nname2: %s", name2);
    printf("\nname3: %s", name3);
    printf("\nname4: %s", name4);
    printf("\nname5: %s", name5);
    strcat(name1, name2);
    printf("\nname1: %s", name1);
    
    strncat(name4, name5, 3);
    printf("\nname4: %s", name4);
    
    return 0;
}

当我 运行 代码时,我得到以下输出:

First name: apple

Second name: elefant

name3: elefant
name4: elefa
name1: apple
name2: elefant
name3: elefant
name4: elefa
name5: app|�
name1: appleelefant
name4: elefaapp

为什么 name5 得到 app|� 而不是只得到 app?此外,有时我得到最后一个 name4,这是 name4name5 的串联,如 elefaapp|�。谁能解释一下这种奇怪的行为?

我已经搜索并阅读了函数文档,但对此一无所知。

来自文档:

https://www.cplusplus.com/reference/cstring/strncpy/

No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow).

一般情况下,使用strncpy

需要手动添加一个'[=10=]'来终止字符串