🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Safe String Appending in C
Append strings in C without overflow: strcat pitfalls, offset copies, bounded helpers and in-place edits.
Building a command, a log line or a device name usually means gluing smaller pieces together, and that is where many firmware bugs are born. If you want to append strings in C without trashing the stack, you need to know exactly what strcat expects, how to write the end of a string by hand, and how to refuse a copy that does not fit. This lecture of our free C programming course walks through each of those, with real compiler messages and verified output.
What You Will Learn
- Why
strcat(buf, '?')is wrong and what the compiler tells you - How
strcpy(dst + strlen(dst), src)works and why it equalsstrcat - How to write a bounded append helper that rejects oversized input
- How to edit a string in place by moving a pointer with
++,+=and subscripts - How to step through a string in strides without reading past the NUL
Prerequisites
You should understand NUL terminated strings, strlen, strcpy and basic pointer movement from the earlier lectures in this free C tutorial. The previous lecture on string literals is also helpful, because several examples start from a literal and copy it into an array. Compiler used: GCC 13, -std=c11 -Wall -Wextra.
How to Append Strings in C: the Basic Rule
To append strings in C correctly, remember that appending means finding the current terminating NUL, writing the new characters over it, and putting a fresh NUL after them. Two facts matter. First, the destination must be a modifiable array (or heap memory), never a literal. Second, the destination must be large enough for the old text, the new text and one extra byte for the terminator. C will not check either fact for you, which is why embedded C programming style guides are so strict about bounded string operations.
Before and after appending a question mark
Appending a Single Character: A Common Mistake
A frequent beginner attempt is to append one character by passing a character constant to strcat:
#include <string.h>
#include <stdio.h>
int main(void)
{
char buf[16] = "AT+CSQ";
strcat(buf, '?');
printf("%s\n", buf);
return 0;
}
The function expects a pointer to a string, but '?' is an integer constant with the value 63. GCC warns:
p44bad.c:7:17: warning: passing argument 2 of 'strcat' makes pointer from integer without a cast [-Wint-conversion]
7 | strcat(buf, '?');
| ^~~
| |
| int
note: expected 'const char * restrict' but argument is of type 'int'
On newer compilers (GCC 14 and later, and recent Clang) this is a hard error, and that is good news because the old behaviour was to treat the number 63 as a memory address and crash. The fix is to pass a string, strcat(buf, "?"), or to write the character yourself:
size_t n = strlen(buf);
buf[n] = '?';
buf[n + 1] = '\0';
How to Append Strings in C With Offset Copies
You can build strcat yourself from two simpler functions: find the end with strlen and copy to that address. The expression strcpy(dst + strlen(dst), src) is exactly an append. Understanding this removes the mystery from strcat and helps you notice its biggest weakness: it walks the destination from the start every time. Appending ten pieces one after another scans the growing string ten times. For long messages on a slow core, remember the end position in a variable and copy straight to it.
The second weakness is the one that matters for safety. Neither strcat nor this offset form knows how big the destination is. That is why we wrap the operation in a helper.
A Bounded Append Helper
The helper below receives the capacity of the destination, calculates whether the result will fit, and refuses to copy when it will not. It returns a boolean so the caller can react.
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
static bool append_safe(char *dst, size_t cap, const char *src)
{
size_t used = strlen(dst);
size_t need = strlen(src);
if (used + need + 1 > cap)
return false;
memcpy(dst + used, src, need + 1);
return true;
}
int main(void)
{
char cmd[12] = "AT";
printf("add +CSQ : %s\n", append_safe(cmd, sizeof cmd, "+CSQ") ? "ok" : "rejected");
printf("add ? : %s\n", append_safe(cmd, sizeof cmd, "?") ? "ok" : "rejected");
printf("add +CREG: %s\n", append_safe(cmd, sizeof cmd, "+CREG") ? "ok" : "rejected");
printf("cmd = [%s] len=%zu cap=%zu\n", cmd, strlen(cmd), sizeof cmd);
return 0;
}
add +CSQ : ok
add ? : ok
add +CREG: rejected
cmd = [AT+CSQ?] len=7 cap=12
Walk through the arithmetic. After the second call the buffer holds seven characters. Adding +CREG needs five more characters plus the terminator, so 7 + 5 + 1 = 13, and the capacity is only 12. The helper returns false and leaves the buffer untouched, which is exactly the behaviour you want. Notice that it copies need + 1 bytes with memcpy so the NUL travels along and no second step is needed.
Capacity check performed by the helper
Warning: measure capacity with sizeof only where the array is declared. Inside a function that receives a pointer, sizeof returns the pointer size, so always pass the capacity as an argument, as the helper does.
Editing a String In Place With a Moving Pointer
Appending is only one way to change text. Often you only need to patch a character in the middle, for example switching a port letter in a configuration line. Pointer movement with ++ and += and subscripts on the pointer make that easy. Subscripting a pointer, p[5], is just shorthand for *(p + 5), measured from wherever p currently points rather than from the start of the array.
#include <stdio.h>
int main(void)
{
char line[] = "pin=GPIOA5";
char *p = line;
p++;
p += 2;
printf("p now : %s\n", p);
*p = ':';
p[5] = 'B';
printf("line : %s\n", line);
printf("p : %s\n", p);
return 0;
}
p now : =GPIOA5
line : pin:GPIOB5
p : :GPIOB5
Trace it carefully. The array starts as p i n = G P I O A 5. After p++ the pointer is at index 1 and after p += 2 it is at index 3, the equals sign. Writing ':' replaces that character. Then p[5] means index 3 plus 5, which is index 8, the letter A, and it becomes B. Because p points into line, both views of the string show the edit, as the last two output lines prove.
Pointer positions during the edit
Stepping Through a String in Strides
Sometimes you want every third character, perhaps to sample interleaved data. A tempting loop is while (s[i]) { use(s[i]); i = i + 3; }. It has a hidden flaw: when the length is not a multiple of three, the index jumps over the NUL and the loop keeps reading memory that does not belong to the string. The safe pattern measures the length first and compares the index with it.
#include <stdio.h>
#include <string.h>
static void sample_every_third(const char *s)
{
size_t i, len = strlen(s);
for (i = 0; i < len; i += 3)
printf("%c ", s[i]);
printf("\n");
}
int main(void)
{
sample_every_third("A1B2C3D4E5");
sample_every_third("ABCDE");
return 0;
}
A 2 D 5
A D
The ten character string yields indexes 0, 3, 6 and 9, and the five character string yields 0 and 3. The index 6 in the second case is never touched because the test i < len fails first. The unsafe loop would test index 6 of a five character string, which is outside the array.
Common Mistakes When You Append Strings in C
| Mistake | Result | Fix |
|---|---|---|
strcat(buf, 'c') | Integer treated as address, warning or error | Use "c" or write the byte and NUL by hand |
| Destination too small | Buffer overflow, corrupted neighbours | Check used + need + 1 <= cap first |
| Appending to a literal | Crash on write | Start from a char array |
| Uninitialised destination | strlen reads garbage, append lands anywhere | Initialise with = "" or buf[0] = '\0' |
Stride loop tested with while (s[i]) | Index skips the NUL and reads past the end | Compare i with strlen(s) |
Best Practices for Safe String Appending
- Always pass the destination capacity along with the pointer.
- Prefer
snprintfwhen you are combining text and numbers, because it takes a size and always terminates. - Avoid
strncatandstrncpyas quick fixes; their size arguments mean different things andstrncpymay leave no terminator. - Keep the current end position in a variable when you append many pieces, instead of rescanning with
strlen. - Decide what a rejected append means for your program: retry, truncate on purpose, or report an error.
Security considerations: when you append strings in C without a size check, you invite a classic bug: unchecked appends are among the oldest sources of stack smashing bugs in network facing firmware. A single missing capacity test on a command received over UART or Bluetooth can give an attacker control of the device. Performance: the helper above calls strlen twice, which is cheap for short strings, but if profiling shows string building in a hot path, track the length yourself.
Summary and Key Takeaways
- To append strings in C you overwrite the old NUL, copy the new text and place a new NUL, in a modifiable array that is large enough.
strcpy(dst + strlen(dst), src)is the same operation asstrcat.strcattakes a string, never a character constant.- A bounded helper turns silent overflow into a handled error.
- Pointer movement and pointer subscripts let you patch text in place.
- Test stride loops against the length, not against the NUL.
Conclusion
Learning to append strings in C safely is not about memorising library calls. It is about keeping three numbers in your head: how much text you have, how much you want to add, and how much room the buffer offers. Once you track those, functions like strcat, memcpy and snprintf become interchangeable tools. For practice, extend the helper so that it truncates and returns a status code instead of refusing, and test it with an empty source string. This exercise belongs to the larger embedded C programming path of our free embedded C course, where every lecture ends with a small task that you can run on your own computer.
Frequently Asked Questions
How do I append strings in C safely?
Check that the current length plus the new length plus one byte for the NUL fits in the destination array, then copy with memcpy or strcpy. A small helper that takes the destination capacity makes this check routine.
Why does strcat(buf, ‘a’) not work?
strcat expects a pointer to a string as its second argument, but ‘a’ is an integer constant. Pass “a” instead, or set the byte and the terminator manually.
Is strcpy(dst + strlen(dst), src) the same as strcat?
Yes. Both find the end of the destination and copy the source there, including its terminator. Neither checks the destination size.
Should I use strncat or snprintf?
snprintf is usually easier to use correctly because its size is the total buffer size and it always terminates. strncat counts the maximum characters to add, which is a frequent source of off-by-one mistakes.
What happens if the destination buffer is too small?
The copy writes past the end of the array and corrupts whatever follows it in memory. This is undefined behaviour and a well known security vulnerability.
Can I append to a string literal?
No. Literals are read-only and have no spare space. Copy the literal into a char array with enough capacity first.
Why use p[5] on a pointer that is not at the start?
Subscripting a pointer is relative to where it currently points, so p[5] means the character five positions after p. It is convenient when you have already skipped a prefix.
Keep Going With the Free C Course
EmbeddedPathashala is a free C programming course and free embedded C course built for students. Practice every example on your own machine, then move on to the next lecture.
div>
2 Comments