How to use and Implement own strncat in C

How to use and Implement own strncat in C_CPP

The strncat function appends n characters from the array pointed to by s2 (source) to the end of the string pointed to by s1 (destination). The initial character of s2 overwrites the null character at the end of s1. It means character s2[0] replaces the null terminator at the end of s1.

Syntax strncat in C:

//Syntax of strncat in C

char *strncat(char * restrict s1,
const char * restrict s2,
size_t n);

Parameters:

s1— pointer to the destination string.

s2— pointer to the source array

n— represents the maximum number of characters to be appended. size_t is an unsigned integral type.

Return:

The strncat function returns the value of s1.

 

Let’s see an example code to understand the functionality of the strncat in C. In this C code, I am appending the 4 characters from an array “src” to the array “dest”.

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

#define SIZE 40

int main()
{
    char dest[SIZE] = "I love Aticleworld";
    char src[SIZE] = ".com";

    //Append 4 char from src to dest
    strncat(dest, src, 4);

    //print dest after appending src
    printf("Dest array = %s\n\n",dest);

    //print src array
    printf("Src array = %s\n\n",src);

    return 0;
}

Output:

strncat in c

 

Some important points you must know before using the strncat in C:

1. You must include string.h header file before using the strncat function in C.

2. When we use strncat(), the size of the destination buffer must be large enough to store the resultant string otherwise the behavior of strncat would be undefined. Let’s see an example code to understand this point.

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


int main()
{
    //dest array size 6
    char dest[6] = "Hello";

    //src array
    char src[] = "Aticleworld.com";


    //Append all char from src to dest
    strncat(dest, src, sizeof(src));

    //print dest after appending src
    printf("Dest array = %s\n\n",dest);

    //print src array
    printf("Src array = %s\n\n",src);

    return 0;
}

Output:

undefined behavior.

Note: strncat does not check for sufficient space in the destination buffer, it is therefore a potential cause of buffer overruns.

 

3. The destination string must not be a literal string. If you do then the strncat() function will try to modify a string literal which is undefined behavior and may cause the program to crash. See the example,

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


int main()
{
    //literal string
    char *dest = "Hello";

    //src array
    char src[] = "Aticleworld.com";

    //Append all char from src to dest
    strncat(dest, src, sizeof(src));

    //print dest after appending src
    printf("Dest array = %s\n\n",dest);

    //print src array
    printf("Src array = %s\n\n",src);

    return 0;
}

 

4. A terminating null character is always appended to the result. Thus, the maximum number of characters that can end up in the array pointed to by s1 is strlen(s1)+n+1.

5. If a null character appears in s2 before n characters are appended, strncat appends all characters from s2, up to the null character. Because n is greater than the length of s2, the length of s2 is used in place of n.  Let’s see an example code,

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

#define SIZE 40

int main()
{
    char s1[SIZE] = "Hello";
    char s2[] = "abc";
    int n = 10;

    printf("s1 length before appending = %d\n\n",strlen(s1));

    //Append n char from s2 to s1
    strncat(s1, s2, n);

    printf("s1 length After appending = %d\n\n",strlen(s1));

    //print s1 after appending s2
    printf("Dest array = %s\n\n",s1);

    //print s2 array
    printf("Src array = %s\n\n",s2);

    return 0;
}

Output:

strncat n less source in c

 

6.) If copying takes place between objects that overlap, the behavior is undefined.

7.) The behavior is undefined if dest is not a pointer to a null-terminated char array.

 

How to write your own strncat in C?

Your compiler/standard library will likely have a very efficient and tailored implementation of the strncat() function. So if not require avoid to create own version of the strncat function.

We can easily implement the strncat() function in C programming. You need to find the trailing null character of the destination string then you need to append the character of the source string including the null character. Let’s create our own version of the strncat() function in C.

Note: Below function only to understand the working of strncat. There is a lot of scenarios that are not handled in this function. You can handle the scenario as your requirement and if possible then use the standard strncat function (library function).

char *my_strncat(char *s1, const char *s2, unsigned int n)
{
    //Pointer should not null pointer
    if((s1 == NULL) && (s2 == NULL))
        return NULL;

    //Create copy of s1
    char *dest = s1;

    //Find the end of the destination string
    while(*dest != '\0')
    {
        dest++;
    }

    //Now append the source string characters
    //until not get null character of s2 or n != 0
    while (n--)
    {
        if (!(*dest++ = *s2++))
        {
            return s1;
        }
    }

    //Append null character in the last
    *dest = '\0';

    return s1;
}

 

 

What is the difference between strcat and strncat (strcat vs strncat)?

Both function and strcat and strncat provided by the C library and both functions are used to append the char array in another string. But besides that, both have some difference, so let’ see a common difference between strncat and strcat.

1. strcat function takes two parameters while strncat takes three parameters.

2. The strcat function append all the characters of the source char array to the destination string while the strncat appends not more than n characters from the source char array.

3. We should use strcat only when we absolutely sure about the source buffer’s size and that the source buffer contains a terminating null character. But with strncat, we don’t need to worry about terminating null character for the source buffer. The destination buffer is large enough for both strcat and strncat.

4. We always try to use strncat in our program because it is safer then strcat. But the value of n must be less than the size of the destination buffer.

 

Recommended Articles for you:

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *