View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

strcat() Function in C: Syntax, Examples, and Common Errors

Updated on 25/04/20253,333 Views

The strcat() function in C is used to join two strings. It adds one string to the end of another. This function is part of the C standard library and comes from the <string.h> header file. It is simple to use but must be handled carefully. 

Explore Online Software Engineering Courses from top universities.

In this article, you will learn how the strcat() function works, how to use it, and what mistakes to avoid. We will also cover the function’s syntax with easy-to-follow examples. These examples will range from basic to advanced levels. Finally, our FAQ section answers real questions that C programmers often ask about string concatenation and strcat().

What is the strcat() Function in C?

The strcat() function in C is a built-in string handling function. It joins one string to the end of another. This operation is known as string concatenation. The function is defined in the standard library <string.h> and is commonly used in C programming for combining two strings.

When you use strcat(), it takes two arguments: a destination string and a source string. It adds the source string at the end of the destination string. This means the null character ('\0') at the end of the destination string is replaced. Then, the characters from the source string are copied, followed by a new null character. 

The destination string must have enough space to store the final combined result. If not, it may lead to undefined behavior like buffer overflow.

Must Explore: Static Function in C: Definition, Examples & Real-World Applications

Syntax of strcat() Function in C

Here’s the syntax of strcat() in C:

char *strcat(char *dest, const char *src);

The function accepts the following parameters:

  • dest: The string to which src will be appended. In simple terms, src will be joined to the end of dest. This destination string should already contain a valid C string and must have enough memory space to store the final result.
  • src: The string that will be added at the end of dest. It should not overlap with dest, or the result will be unpredictable.

Return Value:

The function returns a pointer to the final string dest, which now contains the concatenated result.

Also read the strlen() Function in C article!

strcat() Function in C Examples

In this section, we’ll explore how the strcat() function in C works through practical examples. The examples are divided into three levels - basic, intermediate, and advanced.

Basic Level Example

Let’s begin with a simple example. This shows how to concatenate two strings using strcat() in a safe and readable way.

#include <stdio.h>
#include <string.h> // Required for strcat()

int main() {
char str1[30] = "Good "; // Destination string with enough space
char str2[] = "Morning"; // Source string to be appended

strcat(str1, str2); // Appends str2 to str1

printf("Final String: %s\n", str1); // Output the result
return 0;
}

Output:

Final String: Good Morning

Explanation:

  • str1 is initialized with "Good " and has extra space for the final string.
  • str2 holds "Morning".
  • strcat(str1, str2) joins str2 at the end of str1.
  • A null terminator ('\0') is placed at the end automatically.
  • The final string becomes "Good Morning" and is printed correctly.

Intermediate Level Example

Now let’s see how to combine multiple strings step by step. This example joins three separate strings into one.

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

int main() {
char message[100] = "Welcome "; // First part
char name[] = "to "; // Second part
char place[] = "C Programming!"; // Third part

strcat(message, name); // Add "to " to "Welcome "
strcat(message, place); // Add "C Programming!" to the result

printf("Combined Message: %s\n", message);
return 0;
}

Output:

Combined Message: Welcome to C Programming!

Explanation:

  • We use one destination (message) and two source strings (name, place).strcat() is called twice to join all three strings together.
  • The final string becomes a complete sentence: "Welcome to C Programming!".
  • Sufficient buffer size (100 chars) is provided to prevent overflow.

Advanced Level Example

In this advanced case, we use strcat() with user input. It shows how to safely combine strings entered by the user at runtime.

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

int main() {
char greeting[100] = "Hello, "; // Predefined greeting
char username[50]; // To store user input

printf("Enter your name: ");
fgets(username, sizeof(username), stdin); // Read input including spaces

// Remove trailing newline if present
username[strcspn(username, "\n")] = 0;

strcat(greeting, username); // Append user's name to the greeting

printf("Personalized Greeting: %s\n", greeting);
return 0;
}

Sample Output:

Enter your name: Tarun
Personalized Greeting: Hello, Tarun

Explanation:

  • We take user input using fgets() to support spaces in names.
  • strcspn() removes the trailing newline character from input.
  • strcat() adds the name to "Hello, ", forming a personalized greeting.
  • The output is a dynamic string that changes based on user input.
  • We ensure the buffer (greeting) has enough room for both strings.

Must Explore: Enumeration (or enum) in C article!

When to Use the strcat() Function in C?

You should use the strcat() function in C when you are preparing dynamic messages or handling string-based output. Below are key scenarios where strcat() is the right choice:

  • When you need to combine constant and variable strings: You can merge predefined text with user input or variable values to form a complete message.
  • While creating dynamic output messages: In applications like logging or greeting messages, you can use strcat() to build strings dynamically.
  • To join multiple strings step-by-step: When you have parts of a message stored in different variables, strcat() helps you join them efficiently.
  • In formatting full names or addresses: If user details like first name, last name, and address are stored separately, strcat() helps you form the final readable string.
  • When memory is already allocated in the destination buffer: Use strcat() when your destination string has enough space to hold the final output.

Also Read: Strcpy in C: How to Copy Strings with Examples article!

Common Errors While Using strcat() Function in C

While the strcat() function is useful, it’s important to be cautious of certain pitfalls when using it. Below are the most common errors that developers encounter when working with strcat(), and how to avoid them:

  1. Buffer Overflow: If the destination string does not have enough space to accommodate the source string and the null terminator, it can cause a buffer overflow, leading to unpredictable behavior or crashes.How to avoid: Always ensure that the destination string has enough memory to hold the concatenated result. Use sizeof() or strlen() to check the available space.
  2. Uninitialized Destination String: Using an uninitialized or null pointer as the destination string can cause the program to crash.How to avoid: Initialize the destination string properly before using strcat(). Ensure it points to valid memory.
  3. Overlapping Memory: If the source and destination strings overlap in memory, strcat() can behave unpredictably, leading to corruption of data.How to avoid: Ensure the source and destination do not share the same memory block.
  4. Missing Null Terminator in Destination String: If the destination string is not properly null-terminated, strcat() may not work correctly and can result in incorrect string concatenation.How to avoid: Always make sure the destination string ends with a null terminator before using strcat().
  5. Not Checking for NULL Pointers: Passing a NULL pointer as either the source or destination string can lead to a segmentation fault.How to avoid: Check if either string is NULL before using strcat().

Example: Common Error - Buffer Overflow

Here's an example of an error caused by buffer overflow:

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

int main() {
char str1[10] = "Hello"; // Destination array too small
char str2[] = "World!"; // Source string

strcat(str1, str2); // This may cause a buffer overflow

printf("%s\n", str1); // Output
return 0;
}

Output (likely undefined):

Error or corrupted output, may crash the program

Explanation:

  • str1 is declared with space for only 10 characters, but str2 is 6 characters long.
  • strcat(str1, str2) tries to add "World!" to "Hello", but str1 cannot hold the result.
  • This leads to a buffer overflow, causing unexpected behavior or program crashes.

How to fix it? Ensure the destination string has enough space, like this:

char str1[50] = "Hello";

Conclusion

In this article, we explored the strcat() function in C, which is a powerful tool for concatenating two strings. We have covered the syntax, practical examples, and common errors you might face while using it. To summarize:

  • Key Takeaways:
    • The strcat() function appends the source string to the destination string.
    • Ensure sufficient memory space in the destination string to avoid buffer overflows.
    • The destination string must be properly initialized and null-terminated.
    • Always check for errors like overlapping memory and NULL pointers.

We also provided examples at different levels of complexity, from basic to advanced, to help you understand how strcat() works in various situations. By now, you should be comfortable using this function safely and efficiently in your C programs.

If you follow these practices, you can avoid most common issues and use the strcat() function effectively.

FAQs

1. What does the strcat() function do in C?

The strcat() function in C appends one string to another. It takes two strings: a destination string and a source string. The source string is added to the end of the destination string. The function automatically adds a null terminator to mark the end of the string.

2. What is the syntax for using the strcat() function?

The syntax for using the strcat() function in C is as follows:

char *strcat(char *dest, const char *src);

Here, dest is the destination string that will hold the final concatenated result, and src is the string to be appended. The function returns a pointer to the destination string.

3. How does strcat() handle memory allocation?

The strcat() function does not handle memory allocation. You must ensure that the destination string has enough space to hold the concatenated result. If there is insufficient space, strcat() may cause a buffer overflow, leading to undefined behavior.

4. Can strcat() be used to concatenate strings at runtime?

Yes, the strcat() function in C can concatenate strings at runtime. You can append strings based on user input or program logic. Just ensure the destination string has enough memory space to hold the final result, including the null terminator.

5. What happens if I try to append a string to an uninitialized destination?

If the destination string is uninitialized, using strcat() will likely cause a segmentation fault or undefined behavior. Always initialize the destination string with a valid value and ensure it points to enough memory before using strcat().

6, Is it safe to use strcat() with overlapping strings?

No, using strcat() with overlapping strings can lead to unpredictable behavior. The source and destination strings should not share memory locations. If they do, data corruption may occur. It’s important to ensure that the source and destination strings do not overlap.

7. What is the significance of the null terminator in strcat()?

The null terminator (\0) is essential when using the strcat() function. It marks the end of a string. strcat() appends the source string to the destination string, and the null terminator is automatically added at the end of the concatenated result.

8. Can I concatenate multiple strings with strcat()?

Yes, you can concatenate multiple strings with strcat(). You would need to call strcat() multiple times. Each time, it will append the next string to the growing destination string. Ensure the destination string has enough space to hold the final result.

9. What are the most common errors when using strcat()?

Some common errors with strcat() include buffer overflow, uninitialized destination strings, and using overlapping strings. These errors can lead to crashes or data corruption. Always check that the destination string has enough space and is properly initialized.

10. How can I prevent buffer overflow when using strcat()?

To prevent buffer overflow when using the strcat() function, ensure that the destination string has enough space to accommodate the concatenated result. Use sizeof() to check available memory and make sure there’s enough room for both strings and the null terminator.

11. Why is it important to initialize the destination string before using strcat()?

Initializing the destination string is crucial because it ensures that the strcat() function appends the source string to a valid memory location. If the destination string is uninitialized or NULL, it will cause undefined behavior or crashes during program execution.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.