🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Joining Strings with strcat
Chapter 9, Strings: learn exactly what strcat in C does to memory, why the destination buffer must be prepared, and how to join strings safely in embedded C programming. Free lecture from the EmbeddedPathashala C programming course.
Using strcat in C looks trivial, yet it is behind a surprising number of crashes in firmware and desktop code alike. In this lecture of our free C programming course you will see what concatenation does to the bytes in memory, learn the three rules every call must obey, and practise building device paths and log lines the way professional embedded C programming code does it.
Topics in This Lecture
What You Will Learn
- What string concatenation means at the byte level and how the terminator moves.
- The prototype of strcat and what its return value is for.
- The three rules a safe strcat in C call must satisfy.
- How to check capacity before joining strings in fixed buffers.
- Why repeated concatenation gets slow, and how embedded projects avoid it.
Prerequisites
You need to know how a string is stored as characters followed by a zero byte, how to declare character arrays, and how the previous lecture copied strings with pointers. Basic knowledge of strlen from the earlier lecture is also assumed.
What strcat Does to Memory
To concatenate means to attach one string to the end of another. C has no string type, so the library does it with raw bytes. The prototype from <string.h> is:
char *strcat(char *dest, const char *src);
The function works in three stages. It scans the destination until it finds the terminating zero. It then overwrites that zero with the first character of the source. Finally it copies the rest of the source, including its own terminator, so the combined text ends properly. The source string is never modified, which is why it is declared const.
Buffer Before and After strcat(path, “ttyS1”)
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Before | / | d | e | v | / | \0 | ? | ? | ? | ? | ? | ? |
| After | / | d | e | v | / | t | t | y | S | 1 | \0 | ? |
The question marks are bytes that hold unknown garbage. The terminator that used to sit at index 5 has been replaced by the letter t, and a new terminator now sits at index 10. The buffer had twelve bytes, and the result used eleven of them, so the call is safe.
Three Rules for a Safe strcat in C
| Rule | Why it matters | What breaks if ignored |
|---|---|---|
| The destination must already be a valid string | strcat searches for a zero byte to find the join point | Scan runs past the buffer looking for a zero |
| The destination must be large enough | Needs strlen(dest) + strlen(src) + 1 bytes | Buffer overflow and silent memory corruption |
| Source and destination must not overlap | The copy would overwrite the source as it reads | Undefined behaviour |
The return value is simply the original dest pointer. It exists so that calls can be nested, which you will exploit in the next lecture when you write your own version.
Complete Program: Building a Device Path
This original example builds a device node name from pieces, the kind of task a driver loader or a test script performs. Save it as ep_path.c:
#include <stdio.h>
#include <string.h>
int main(void)
{
char path[24] = "/dev/";
const char *driver = "ttyS";
strcat(path, driver);
strcat(path, "1");
printf("path : %s\n", path);
printf("length : %zu\n", strlen(path));
printf("driver : %s\n", driver);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o ep_path ep_path.c
$ ./ep_path
path : /dev/ttyS1
length : 10
driver : ttyS
Notice that driver still reads ttyS after the calls. The second argument is read, never written. The destination started life with an initialiser, so it was a valid string before the first call, which satisfies the first rule.
Checking Capacity Before You Concatenate
The library will not warn you when the result is too long, so your code must. Compute the required size first, compare it with the buffer size, and refuse the operation when it does not fit:
#include <stdio.h>
#include <string.h>
int main(void)
{
char buf[12] = "temp";
const char *suffix = "_sensor_01";
size_t need = strlen(buf) + strlen(suffix) + 1;
if (need > sizeof buf)
printf("refused: need %zu bytes, have %zu\n", need, sizeof buf);
else
strcat(buf, suffix);
printf("buf = %s\n", buf);
return 0;
}
$ ./ep_guard
refused: need 15 bytes, have 12
buf = temp
The guard turned a would-be memory corruption into a clean, testable failure. In a driver you would return an error code at that point. Notice that sizeof buf works here only because buf is a real array in the same scope. It would give the pointer size if buf had been passed in as a function parameter.
Return Value and Nested strcat Calls
Because strcat returns the destination pointer, you may write strcat(strcat(buf, "a"), "b"). The inner call finishes first and passes the same buffer to the outer call. This works, but long nested lines are hard to read and hard to guard with capacity checks. In production code most teams prefer separate statements with one check in front, so that a reviewer can see at a glance that the buffer is large enough for the total.
Real-World Use Cases of String Concatenation
- Building file and device paths from a base directory and a name.
- Composing log messages with a fixed prefix such as a module tag.
- Assembling AT command strings for a modem before sending them over a UART.
- Creating unique names for resources, such as a task name plus an instance number.
Common Mistakes with strcat
Warning: an uninitialised local array is not a string. Declaring char buf[20]; and calling strcat(buf, "x") is undefined behaviour because the array contains random bytes and no guaranteed terminator. Start with char buf[20] = ""; or set buf[0] = '\0'.
- Forgetting the extra byte. Joining “abc” and “def” needs seven bytes, not six.
- Appending to a string literal.
char *p = "log: "; strcat(p, "x");writes into read-only memory and has no spare room anyway. - Trusting strncat to mean the buffer size. The third argument of
strncatlimits how many characters are appended, not the total buffer size, so you must still subtract the existing length yourself. - Using the result of an earlier strlen after the buffer changed. The length is stale as soon as you concatenate.
Performance Considerations
Every call to strcat starts by scanning the destination from the beginning to find its end. When you append many small pieces in a loop, the work grows with the square of the number of pieces, because the scan gets longer each time. On a small microcontroller running at a modest clock speed, this adds up. The usual remedy is to remember the current end position yourself, or to use snprintf with an offset so each piece is written directly where the last one ended. You will meet that pattern in the lab lecture at the end of this chapter.
Best Practices and Security Notes
- Initialise every destination buffer before its first use.
- Keep the buffer size in a named constant and compare against it before joining.
- Prefer
snprintfwhen you are assembling several parts with formatting, because it takes the buffer size. - Never concatenate data that came from outside the system without checking its length first. Oversized input appended with
strcatis a textbook stack overflow. - Compile with warnings enabled and test with AddressSanitizer on your development computer.
Summary and Key Takeaways
strcat(dest, src)replaces the terminator of dest with the first byte of src and copies src including its terminator.- The destination must be a valid string, large enough, and separate from the source.
- The required size is strlen(dest) + strlen(src) + 1.
- The return value is the original dest pointer, which supports nesting.
- Repeated calls rescan the destination, so track the end yourself for long loops.
Conclusion
Concatenation is one of the most common string operations in C programming for embedded systems, and one of the easiest to get wrong. The call itself is a single line, but safe use depends on discipline around buffer size and initialisation. If you apply the capacity check from this lecture every time, you will avoid a large class of bugs before they reach hardware. Next, you will write your own concatenation function using both array and pointer styles, which shows exactly what the library does behind that one line.
Frequently Asked Questions
What does strcat do in C?
It appends the source string to the end of the destination string by overwriting the destination terminator and copying the source including its terminator.
Does strcat check whether the destination is large enough?
No. The caller must guarantee that the destination has at least strlen(dest) + strlen(src) + 1 bytes.
What does strcat return?
It returns the original destination pointer, which lets you nest calls such as strcat(strcat(a, b), c).
Why is strcat slow for building long strings?
Each call rescans the destination to find its end, so appending many pieces repeats the same scan again and again.
Is strncat the safe version of strcat?
It is safer, but its numeric argument limits the number of characters appended, not the buffer size. You must still calculate the remaining space correctly.
Continue Your Free Embedded C Course
Every lecture in this free C tutorial comes with original examples you can compile in seconds. Move on to the next lecture and write your own concatenation function.

2 Comments