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 src
does 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:
- C Programming Courses And Tutorials.
- CPP Programming Courses And Tutorials.
- Python Courses and Tutorials.
- strdup() in C.
- strerror function in C.
- Use of strncmp function in C programming.
- Strcmp function in C programming.
- How to use strxfrm function in C programming.
- Use of memcmp function with example code.
- How to use memcpy and implement own.
- Implement own memmove in C.
- memmove vs memcpy.
- strcoll in C with example code.
- Implement vector in C.
- How to Use strncpy() and implement own strncpy().