🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Pointer-Based strcpy in C
Chapter 9, Strings: build the classic one-line copy loop, trace it byte by byte, and learn why embedded C programmers never trust an unbounded copy. Part of the free C programming course by EmbeddedPathashala.
Writing strcpy in C with pointers is a rite of passage in every free C programming course, because a single line of code replaces a whole loop and teaches you how pointers, post-increment and assignment expressions work together. In this lecture you will build your own pointer-based copy function, trace it on paper, and then learn why embedded C programming on a microcontroller treats an unbounded copy as a bug waiting to happen.
Topics in This Lecture
What You Will Learn
- How a string copy works in terms of bytes, the null terminator and two moving pointers.
- How to write the compact pointer idiom for strcpy in C and why it stops at the right place.
- How
*dst++is parsed, and why the function should return the original destination address. - How to write a bounded copy that is safe for fixed-size buffers on small devices.
- Which mistakes cause stack corruption, and which compiler flags help you catch them.
Prerequisites
You should already be comfortable with character arrays, the null character '\0', pointer declaration and dereferencing, and pointer increment. If any of these feel shaky, revisit the earlier lectures of the Pointers and Strings chapters of this free embedded C course before continuing.
What Does a String Copy Really Do?
A C string is just a run of bytes that ends with a zero byte. There is no length field and no string object. So copying a string means copying every byte from the source up to and including the terminating zero. If you forget the terminator, the destination is only an array of characters, and the next printf("%s") will happily walk past its end into whatever memory follows.
The copy needs two things at all times: a read position in the source and a write position in the destination. Both advance together, one byte per step. In a loop with array indexes you would write something like this:
void copy_with_index(char dst[], const char src[])
{
size_t i = 0;
while (src[i] != '\0') {
dst[i] = src[i];
i++;
}
dst[i] = '\0'; /* do not forget the terminator */
}
This version is easy to read, but it has two exit steps: the loop test and the separate terminator write. Pointer-based C code folds both into one expression.
The Pointer Idiom for strcpy in C
Here is the compact form. Read it slowly, because every part of the loop header does real work:
char *ep_strcpy(char *dst, const char *src)
{
char *start = dst; /* remember where the copy begins */
while ((*dst++ = *src++) != '\0') /* copy, advance, test */
; /* empty body */
return start;
}
The condition does three jobs in order. First *src is read. Second that value is stored through dst. Third both pointers move forward by one. The value of an assignment expression in C is the value that was stored, so the comparison with '\0' tests the byte that was just copied. When that byte is the terminator, it has already been written, and the loop ends. No separate terminator write is needed.
One Loop Pass Inside the Pointer strcpy
Tracing the Copy of the String “OK”
Take a source holding the three bytes 'O', 'K', '\0'. The loop runs three times:
Trace Table: Copying the Two Letter String OK
| Pass | Byte read from src | Written to dst | Loop continues? |
|---|---|---|---|
| 1 | ‘O’ | dst[0] = ‘O’ | Yes, value is non-zero |
| 2 | ‘K’ | dst[1] = ‘K’ | Yes, value is non-zero |
| 3 | ‘\0’ | dst[2] = ‘\0’ | No, value is zero, loop ends |
Notice that the destination needs room for three bytes, not two. A string of length n always needs n + 1 bytes of storage.
How *dst++ Is Parsed
New learners often ask whether *dst++ increments the pointer or the character. The answer comes from precedence: postfix ++ binds tighter than unary *, so the expression means *(dst++). The pointer is advanced, but the value used is the one at the old address.
| Expression | Meaning | Effect on the pointer |
|---|---|---|
*dst++ | Use the byte at dst, then advance dst | Moves forward by one element |
(*dst)++ | Increment the byte that dst points to | Pointer unchanged |
*++dst | Advance dst first, then use the byte | Moves forward by one element |
Complete Program: Build and Run
Save the following as ep_copy.c. It is an original example that copies an interrupt name into a small buffer, and it prints the return value of the function directly to show why returning the start address is useful.
#include <stdio.h>
char *ep_strcpy(char *dst, const char *src)
{
char *start = dst;
while ((*dst++ = *src++) != '\0')
;
return start;
}
int main(void)
{
char tag[16];
printf("copied: %s\n", ep_strcpy(tag, "gpio_irq"));
return 0;
}
Compile with warnings turned on, then run:
$ gcc -std=c11 -Wall -Wextra -o ep_copy ep_copy.c
$ ./ep_copy
copied: gpio_irq
The buffer holds 16 bytes and the text needs 9 (eight characters plus the terminator), so the copy fits with room to spare.
Why Return the Original Pointer?
If the function returned dst after the loop, the caller would receive an address one byte past the terminator, which is useless and may even be out of bounds. That is why the function saves start at the top. Returning the original address lets callers pass the result straight into another call, as the printf above did. The standard library function does the same, and you will use the habit again when you write your own concatenation function in a later lecture of this free C tutorial.
A Safer Bounded String Copy in C
The big weakness of strcpy is that it never asks how large the destination is. If the source is longer than the buffer, the extra bytes overwrite neighbouring variables, saved registers or return addresses. On a microcontroller without a memory protection unit nothing stops it, and the symptoms appear far away from the real bug. A bounded version takes the capacity as a parameter and always leaves room for the terminator:
#include <stdio.h>
#include <stddef.h>
size_t ep_copy_bounded(char *dst, size_t cap, const char *src)
{
size_t i = 0;
if (cap == 0)
return 0;
while (i + 1 < cap && src[i] != '\0') {
dst[i] = src[i];
i++;
}
dst[i] = '\0';
return i;
}
int main(void)
{
char small[6];
size_t n = ep_copy_bounded(small, sizeof small, "temperature");
printf("stored %zu chars: %s\n", n, small);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o ep_bounded ep_bounded.c
$ ./ep_bounded
stored 5 chars: tempe
The function silently truncates the text, and it reports how many characters were stored, so the caller can detect truncation by comparing the result with the source length. For a real driver you would treat truncation as an error code instead of continuing with half a name.
Real-World Use Cases
- Copying a device name such as a sensor label into a fixed-size field of a configuration structure.
- Moving a command word from a UART receive buffer into a parser buffer before you modify it.
- Loading a default string from flash into a RAM buffer that the user can later edit.
- Building log prefixes and short protocol strings in bare-metal firmware where no heap exists.
Common Mistakes and Troubleshooting
Warning: most strcpy bugs are capacity bugs. Count the terminator every time.
- Destination too small. Copying an eight character name into a buffer of eight bytes writes the terminator one byte out of bounds. Always allocate length plus one.
- Uninitialised destination pointer. A
char *p;that points nowhere is not a buffer. Copying through it writes to a random address. - Destination is a string literal. Literals may live in read-only memory, so the first write can fault. Use a character array instead.
- Overlapping buffers. A string copy with overlapping source and destination is undefined behaviour. Use
memmovewhen overlap is possible. - Using sizeof on a pointer parameter. Inside a function,
sizeof dstis the size of a pointer, not of the buffer. Pass the capacity explicitly.
Best Practices, Performance and Security
Prefer bounded copies in all new firmware code and check the returned count. Keep every buffer size in one named constant so the declaration and the copy call can never disagree. On the performance side, the hand-written loop is rarely faster than the library routine: a good C library copies a word at a time, and a modern compiler can turn a simple loop into an optimised sequence. Write your own version to learn, and use the vetted library or a tested project helper in production.
From the security point of view, unchecked copies are the classic cause of stack buffer overflows. Compile with -Wall -Wextra, enable -fstack-protector-strong on application-class targets, and run tests under AddressSanitizer on your development machine with -fsanitize=address. These tools turn silent corruption into an immediate, readable error report.
Summary and Key Takeaways
- A string copy must include the terminating zero byte, so the destination needs length + 1 bytes.
- The loop
while ((*dst++ = *src++) != '\0')reads, writes, advances and tests in one expression. *dst++means*(dst++): the pointer moves, the old byte is used.- Save the starting address and return it so calls can be chained.
- Bounded copies with an explicit capacity protect small devices from overflow bugs.
Conclusion
You now understand strcpy in C from the byte level up. The compact pointer loop is elegant, but the real lesson is the contract behind it: the caller owns the buffer, and the function cannot check its size. That single fact explains many field failures in embedded C programming, and it is the reason this free embedded C course keeps returning to capacity checks. In the next lecture you will look at concatenation, where the same contract becomes even easier to break.
Frequently Asked Questions
Why does the pointer version of strcpy in C not need a separate terminator write?
The loop condition tests the byte that was just copied. The terminator is copied like any other byte, and the loop stops right after it is stored.
Is strcpy safe to use in embedded firmware?
Only when you can prove that the destination is large enough, for example because the source is a constant of known length. For input that comes from a UART, a network or a file, use a bounded copy.
What is the difference between strcpy and memcpy?
strcpy stops at the first zero byte and needs no length. memcpy copies exactly the number of bytes you request and does not look at the contents.
Why does the function take const char * for the source?
It promises not to modify the source. This lets you pass string literals and read-only data without a compiler warning.
Can I copy a string by assigning one array to another?
No. An array name is not assignable in C, so you must copy the elements with a loop or a library function.
Keep Going With the Free C Programming Course
This free C tutorial is built for students who want to learn C programming for embedded systems without paying for a course. Continue with the next lecture and practise every example on your own machine.

2 Comments