Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is C strcpy()?
3.
How to use C strcpy() Function?
3.1.
Syntax of strcpy() in C
4.
Internal Working of strcpy() in C
5.
Parameter of strcpy() in C
6.
Return Values strcpy() in C
7.
Exceptions of C strcpy()
8.
Example
8.1.
1. Buffer Overflow
8.2.
2. Null-Termination Issue:
8.3.
3. No Size Checking:
9.
How does the strcpy() Function Work?
9.1.
Implementation in C
9.2.
C
9.3.
Explanation 
9.4.
Common Errors 
10.
How to Copy a String Using strcpy() Function in C?
10.1.
C
11.
Advantages of  Strcpy() Function in C
12.
Disadvantages of  Strcpy() Function in C
13.
Frequently Asked Questions
13.1.
What is the strcpy function used for?
13.2.
What is the strcpy function in C?
13.3.
Which library is strcpy in?
13.4.
How to copy a string in C using strcpy?
14.
Conclusion 
Last Updated: Mar 27, 2024
Medium

Strcpy() in C

Author Gunjan Batra
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In the realm of C programming, the strcpy() function stands as a fundamental tool, quietly performing a critical role in manipulating strings. As one of the standard library functions, strcpy() is used to copy the contents of one string to another, and its seemingly straightforward nature belies the intricacies it carries beneath the surface.

strcpy function in c

This blog will dive into a strcpy() function in C. We will learn the functioning of the strcpy function, its implementation, programs, and many more.

Also see: C Static Function

What is C strcpy()?

The purpose of the strcpy function is to copy the characters from one string to another. It is essential to understand that the function does not create any new string; it just copies the one-character array into another character array, i.e., string. Developers mainly use the function for manipulating tasks, text, phrases, etc. 

Strcpy is the most commonly used function in strings. It takes the content of the source string, including the important null character that marks the end of the string, and replaces the previous content of the destination string with this copied version. It ensures the destination string is properly terminated with a null character. 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How to use C strcpy() Function?

The strcpy() function in C is like a copy-paste tool for words. Imagine you have two boxes (strings), and you want to copy the words from one box to another. strcpy() helps with that. You just tell it which box to copy from and which box to copy to.

Here's a simpler breakdown:

1. Declare Boxes: First, you declare your two boxes (strings) - one for the original words (source) and another for the copied words (destination).

char source[] = "Hello, World!";
char destination[20]; // Make sure it's big enough to hold the source

 

2. Use strcpy(): Next, you use strcpy() to copy the words. Think of it like saying, "Hey, strcpy(), take the words from the source box and put them in the destination box."

strcpy(destination, source);

 

3. Display the Result: Finally, you can check if it worked by looking at the words in both boxes.

printf("Source: %s\n", source);
printf("Destination: %s\n", destination);

Syntax of strcpy() in C

Before we go further in the article, it is crucial to understand the syntax for using the strcpy function in C. Below is the syntax for using the strcpy function in C.

char* strcpy(char *destination, const char * source)

 

Now, let us understand the above syntax in detail:

The strcpy function takes two char pointer arguments and returns a pointer to the destination string. The first argument is a char pointer array to which the first argument array content will be copied. The second argument is a char pointer which has the string that will be copied in the first argument.  
 

char * destination: This is the character array in which the source content will be copied. In the destination array, the content of the source will be copied. 
 

const char * source: The const char * source is the string whose content will be copied to the destination string. 

Return Type: The return type for the strcpy function is a char pointer, i.e., destination string. 

Also read about strcat() function in C and  Short int in C Programming

Internal Working of strcpy() in C

The internal working of strcpy() function is iterating over the each character of the source string and copying it to the referring position of the destination string till it gets the null character i.e. '\0'. The null character makes the end of the string. 

Parameter of strcpy() in C

The strcpy() function takes two parameters:

Destination: This is a pointer to the destination string that will be copied. The destination parameter must have a valid C string. The destination pointer should not be NULL.

Source: This is a pointer to the source string that will be copied. The source string must be a valid C string which means it should be null-terminated. The source pointer should not be NULL.

Return Values strcpy() in C

The strcpy() function in C returns a pointer to the destination string. The return value of this function is the same as the value of the destination parameter we passed to the function. The return value of strcpy() is not the result of the copying operation, it is a reference to the destination string.

Exceptions of C strcpy()

The strcpy() function in C does not perform bounds checking, making it prone to buffer overflow issues. Here are some common exceptions and potential problems associated with the strcpy() function:

1. Buffer Overflow: If the destination array is not large enough to accommodate the source string along with its null-terminator, strcpy() will overwrite adjacent memory, leading to undefined behavior.

2. Null-Termination: Ensure that the destination array is properly null-terminated. If the source string is longer than the destination array, the null-terminator might be truncated, resulting in an unterminated string.

3. No Size Checking: strcpy() does not check the size of the source or destination arrays. It blindly copies until it encounters a null-terminator in the source string.

Example

Let's look at examples of exceptions and potential issues that can arise when using the strcpy() function in C:

1. Buffer Overflow

char source[] = "Too long string";
char destination[10];  // Too small
strcpy(destination, source);  // Buffer overflow

2. Null-Termination Issue:

char source[] = "Hello, World!";
char destination[5];  // Too small
strcpy(destination, source);  // Null-termination issue

3. No Size Checking:

char source[] = "Hello";
char destination[10];
strcpy(destination, source);  // No size checking

How does the strcpy() Function Work?

Now that we have learned about the parameter and syntax let us further understand the functioning of the strcpy function. 

The content from the source string will be copied to the destination string with memory allocated at a different location.

Implementation in C

  • C

C

#include <stdio.h>
#include<string.h>
int main()
{
   char string1[] = "Coding Ninjas";
   char string2[20];
   strcpy(string2,string1);
   printf("%s\n",string2);
   return 0;
}

Output:

After successfully executing the above code, the output we receive is given below:

output

Explanation 

Now, let’s understand the code we have written above:

  • Include the header file string.h to use the strcpy function in C. 
     
  • Two character arrays of the same size or the destination array greater than the source array are declared. In the above code, we have two arrays, string1 and string2. The string1 array is defined with strings =” Coding Ninjas”. 
     
  • Use the strcpy function and pass two parameters. The first parameter is the character array in which the string will be copied. In the second parameter, we have the source string. In the above code, the string2 is the destination array in which the string1, i.e., Coding Ninjas, will be copied. 
     
  • printf statement is used to print the copied string. 

Common Errors 

You may encounter a few common errors when you use the strcpy function in C. 

  • Buffer error: It is important to note that the destination array must have an equal or greater size than the source string. This further means if the destination array size is smaller, the string that will be occupied will not contain the null terminator character. This is because if the destination string does not hold enough space to hold the data, it can cause the buffer overflow error, which directly or indirectly will result in improper performance of the strcpy function or lead to a program crash. 
     
  • Null pointer issue: In case the source or destination string is a null pointer, the strcpy function will cause for segmentation error. To avoid this, you must ensure both strings have a valid null terminator. 
     
  • Uninitialized array: When the destination array is uninitialized, it occupies space in an unpredictable location. To avoid this error, you must specify the size of the destination array. 
     
  • String overlapping: If in case the source and destination strings may overlap, the strcpy function does not copy the string correctly. So it is vital that string overlapping must be avoided. 

How to Copy a String Using strcpy() Function in C?

To copy a string using the strcpy() function in C, you can follow the below steps:

Step 1: Include the string.h header file

Step 2: Now, you need to declare the source string and the destination array.

Step 3: Now, you need to call the strcpy() function and pass the destination array and the source string as arguments.

Step 4: Last step is to print the copied string as shown in the below program,

  • C

C

#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, world!";
char destination[20];
strcpy(destination, source);
printf("Copied string: %s\n", destination);
return 0;
}

Output:

Copied string: Hello, world!

 

Advantages of  Strcpy() Function in C

  • It is easy to use and a simple function that can be used to copy strings fast and easily.
  • It only requires a single pass through the source string to copy, and it is relatively fast.
  • It is a standard library function, so it is widely available and portable across different compilers and platforms.

Disadvantages of  Strcpy() Function in C

  • It does not handle null characters within the source string properly. If the source string contains a null character, strcpy will stop copying, even if additional characters are in the source string.
  • If the source and destination strings overlap. It does not handle overlapping strings properly. The behavior of strcpy is undefined.
  • It does not check the size of the destination buffer, so it is possible to overwrite the buffer and cause a buffer overflow if the source string is longer than the destination buffer. This can lead to security vulnerabilities and other problems.

    Must Read Passing Arrays to Function in C

Frequently Asked Questions

What is the strcpy function used for?

The strcpy function in C is used for copying the contents of one string to another.

What is the strcpy function in C?

The strcpy function in C is a standard library function used for string copying.

Which library is strcpy in?

The strcpy function is part of the C Standard Library, and its declaration is in the string.h header file.

How to copy a string in C using strcpy?

Use the syntax strcpy(destination, source) to copy the characters from the source string to the destination string in C. Ensure destination has enough space.

Conclusion 

In this article, we have thoroughly discussed the C strcpy(). The strcpy() function in C serves as a fundamental tool for string manipulation. While powerful, its lack of bounds checking demands cautious use. Developers should be mindful of potential buffer overflow issues and consider safer alternatives like strncpy() for robust and secure string handling.

To know more about the C programming language, head to;

Strings in C

Getch in C

Bubble Sort Program in C

Strcmp() Function in C: To Compare Strings

Strcat() Function in C: Concatenate String

Conditional Operator in C

Ternary Operator in C

strstr Function in C

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our coursesrefer to the mock test and problems look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

Previous article
getch() Function in C
Next article
Arrays
Live masterclass