cstring.hstrncmp

string.h functions - strncpy and strncat strange behaviour


I was testing some of the string.h function and found a strange behaviour when using the functions strncpy and strncat.

#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;
}

When I run the code, I get the following output:

First name: apple

Second name: elefant

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

Why is name5 getting app|� instead of just getting app? Besides, sometimes I was getting the last name4, which is the concatenation of name4 with name5, as elefaapp|�. Can anyone explain this strange behavior, please?

I already searched and read the functions documentation, but I have no clue regarding that.


Solution

  • From the documentation:

    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).

    In general, you need to manually add a '\0' to terminate the string when using strncpy