strcpy in C

In this blog post, you will learn what is the strcpy() and how to use the strcpy() function in C to copy strings with the help of programming examples.

 

What is strcpy in C?

The strcpy function copies the string pointed to by src (including the terminating null character) into the array pointed to by dest. The strcpy() declares in the header file <string.h>.

 

Syntax strcpy in C:

char *strcpy(char * restrict dest, const char * restrict src);

 

strcpy Parameters:

The strcpy() function accepts the following parameters:

dst — pointer to the destination object.

src — pointer to the source object (null-terminated byte string).

 

strcpy() return value:

The strcpy function returns the value of dest.

 

Example program to describe how to use strcpy in C:

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

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

int main()
{
    char src[20] = "Aticleworld.com";
    char dest[20] = {0};

    // copying dest to src
    strcpy(dest, src);

    //print dest
    printf("%s",dest);

    return 0;
}

Output:

Aticleworld.com

Explanation:

In the above code with the help of strcpy, we are copying the string bytes from src to dest buffer. After the copy, we are printing the dest buffer.

 

Undefined Behavior of strcpy() :

The behavior of strcpy() is undefined if:

1. Copying takes place between objects that overlap.

2.dest array is not large enough to store the src string bytes.

3.src is not a pointer to a null-terminated byte string.

4.dest is not a pointer to a character array.

 

Is strcpy safe to use?

No, the strcpy is not safe to use.  There are the following reasons that make strcpy unsafe.

1. The strcpy() function does not check for sufficient space in the destination before it copies the source, it is a potential cause of buffer overruns. Consider the below example,

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

int main()
{
    char src[20] = "Aticleworld.com";

    /*
    Here destination is not large
    enough to store the src. so the
    behaviour of strcpy is unspecified.
    */
    char dest[5] = {0};

    // copying dest to src
    strcpy(dest, src);

    //print dest
    printf("%s",dest);

    return 0;
}

Output:

Undefined Behaviour

2.strcpy depends on a trailing ‘\0’ that also makes it unsafe.

 

Note: The strncpy function is a safer version of strcpy to copy a string from a source to a destination buffer. But strncpy is also not much safer than strncpy_s.

 

Recommended Articles for you:

Leave a Reply

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