strndup in C

In this blog post, you will learn about the strndup in C with the help of programming examples.

 

strndup() in C:

The strndup function creates a copy of the string pointed to by src. The copy of bytes from src to allocated space is up to the null character or given size, whichever comes first.

If the array pointed to by srcdoes not contain a null within the first size characters, a null is appended to the copy of the array. But if the null terminator is not encountered in the first size bytes, it is added to the duplicated string.

The returned pointer must be passed to free to avoid a memory leak. If an error occurs, the strndup returns a null pointer.

 

Syntax strndup in C:

The strndup() declare in <string.h> header file. The following is the syntax of the strndup function in C.

char *strndup(const char *s, size_t size);(since C23)

 

strndup Parameters:

The strndup() the function accepts the following parameters:

src — pointer to the null-terminated byte string to duplicate.

size – max number of bytes to copy from src.

 

strndup return value:

The strndup() function returns a pointer to the first character of the created string. The returned pointer must be passed to free() function to deallocate the allocated memory. If no space can be allocated the strndup function returns a null pointer.

 

Example program to describe how to use strndup in C:

The following program illustrates the working of the strndup() function in the C language.

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

int main()
{
    const char *s1 = "Aticleworld.com";
    char *s2 = strndup(s1, 11);
    if(s2 != NULL)
    {
        printf("s2 = %s\n", s2);
        // calling free()
        free(s2);
    }
    return 0;
}

Output: Aticleworld

 

Recommended Post: