How to Copying Strings Safely in C- Free Online C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Copying Strings Safely in C

Chapter 9, Lecture 11 of the free C programming course: strcpy, overflow, strncpy and safer alternatives

9.3.3
Chapter section
Lecture 11
Free C tutorial
Intermediate
Level

Learning to copy strings in C safely is one of the most valuable skills in this free C programming course. C will not let you assign one array to another with =, so every copy goes through a library function or a loop, and each of those can overflow the destination if you are careless. In this lecture you will understand strcpy() completely, build your own version, and then learn the bounded alternatives that embedded C programming demands.

The examples are original, compiled with gcc -std=c17 -Wall -Wextra, and the output shown is real. If you are using this free C tutorial to prepare for firmware or driver work, treat this lecture as the one to read twice.

What You Will Learn

  • How strcpy works and why it copies the terminator too
  • Why assigning one array to another is a compile error
  • Why you cannot write into a string literal
  • How to write ep_strcpy() with a one-line loop
  • How buffer overflow happens and what it costs in a real device
  • How to copy strings in C safely with snprintf, strncpy, strlcpy and memcpy

Prerequisites

You should know the null terminator, strlen() from lecture 9 and pointer increment. A short refresher: *p++ reads the value, then moves the pointer one element forward. We use it in the copy loop below.

How strcpy Helps Copy Strings in C

The prototype is char *strcpy(char *dst, const char *src);. It copies every character of src, including the terminator, into the memory that dst points to, and returns dst. The return value exists so you can chain calls, for example puts(strcpy(buf, "ok")), though most code ignores it.

Notice what the function does not do: it never asks how big the destination is. It copies until it has moved the terminator, however many bytes that takes. The caller carries the whole responsibility for making the destination large enough.

strcpy(dst, “v1.4”) copies five bytes
srcv1.4\0
copyv1.4\0
dstv1.4\0rest of dst unchanged

Because the terminator is copied, the destination needs strlen(src) + 1 bytes. Forgetting that one extra byte is the most common off-by-one error in C.

Why Arrays Cannot Be Assigned

In C an array name is not a variable you can assign to; it is a fixed address. So b = a; with two arrays is rejected by the compiler. With two pointers the statement compiles but copies only the address, leaving both pointers aimed at the same text. Neither does what a beginner expects, which is a copy of the characters. That job belongs to strcpy.

String literals are read-only

A literal such as "New" is stored in a read-only region, often flash on a microcontroller. You may read it, but writing to it is undefined behaviour and on many systems crashes immediately. That makes the destination argument the important one to watch:

char buf[8];
strcpy(buf, "New");        /* OK: destination is writable memory */

strcpy("New", buf);        /* BUG: destination is a literal, wrong argument order */

char *p = "York";          /* p points at read-only text */
p[0] = 'N';                /* undefined behaviour: modifies a literal */

char q[] = "York";         /* q is a writable copy of the characters */
q[0] = 'N';                /* fine */

The last two blocks look similar but behave differently. A pointer initialised with a literal aims at the shared read-only text, while an array initialised with a literal holds its own writable copy. When you intend to change the text, use the array form.

Writing Your Own ep_strcpy()

The whole function fits in one loop. The condition performs the copy and the test together: the assignment expression has the value of the character just stored, so the loop ends right after the terminator has been copied.

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

char *ep_strcpy(char *dst, const char *src)
{
    char *ret = dst;
    while ((*dst++ = *src++) != '\0')
        ;
    return ret;
}

int main(void)
{
    char a[16], b[16];
    const char *fw = "v1.4.2";

    ep_strcpy(a, fw);
    strcpy(b, a);
    printf("a = %s, b = %s\n", a, b);

    /* bounded copy that always terminates */
    char small[6];
    snprintf(small, sizeof small, "%s", "temperature");
    printf("small = [%s] (len %zu)\n", small, strlen(small));

    /* strncpy trap: no '\0' written when src is too long */
    char trap[4];
    strncpy(trap, "ABCDEFG", sizeof trap);
    printf("trap[3] is %s\n", trap[3] == '\0' ? "terminator" : "NOT a terminator");
    trap[sizeof trap - 1] = '\0';
    printf("trap fixed = [%s]\n", trap);
    return 0;
}

Compile and run it. The two warnings are deliberate: they come from the intentional truncation demonstrations further down, and GCC is right to point them out.

$ gcc -std=c17 -Wall -Wextra -o ex11_strcpy ex11_strcpy.c
ex11_strcpy.c: In function 'main':
ex11_strcpy.c:28:5: warning: 'strncpy' output truncated copying 4 bytes from a string of length 7 [-Wstringop-truncation]
ex11_strcpy.c:23:5: note: 'snprintf' output 12 bytes into a destination of size 6
$ ./ex11_strcpy

Expected output:

a = v1.4.2, b = v1.4.2
small = [tempe] (len 5)
trap[3] is NOT a terminator
trap fixed = [ABC]

Line one shows the library copy and your own copy producing identical text. Line two shows snprintf cutting temperature down to tempe: five characters plus the terminator fit in the six-byte array, and the string is still valid. Lines three and four expose the strncpy trap, explained next.

When Copy Strings in C Goes Wrong: Buffer Overflow

Imagine a six-byte field for a device label and a fifteen-character source. strcpy happily writes all sixteen bytes, and the extra ten land on whatever variable sits next in memory. On a PC that can corrupt a neighbouring variable or a return address; on a microcontroller without memory protection it can silently flip a motor-control flag.

strcpy into a buffer that is too small
label[6]temper
overflowature\0these bytes hit the next variable

Overflow is a security issue too

Overwriting adjacent memory with attacker-controlled text is the classic route to remote code execution in networked devices. Treat every copy from an external source, such as a UART, radio packet or file, as untrusted and bounded.

Safer Ways to Copy Strings in C

FunctionAlways terminates?Pads with zeros?Detects truncation?Notes
strcpyYesNoNoUnbounded; only safe when the size is proven
strncpyNoYes, up to nNoDesigned for fixed-width fields, not as a safe strcpy
snprintf(d, n, "%s", s)YesNoYes, via the return valueStandard C, easy and safe
strlcpyYesNoYes, via the return valueBSD origin; in glibc from 2.38 and many embedded libraries
memcpyNot applicableNoNot applicableFastest when the length is already known

The strncpy trap

The name suggests a safe strcpy, but it is not. When the source is as long as or longer than the limit, strncpy copies n characters and writes no terminator. Later code that treats the buffer as a string reads past its end. The example proves it: trap[3] is not a terminator until the program adds one by hand.

If you must use strncpy, always terminate manually: dst[sizeof dst - 1] = '\0';. In new code prefer snprintf, which terminates automatically. Its return value is the length it wanted to write, so truncation is easy to detect:

int n = snprintf(label, sizeof label, "%s", source);
if (n < 0 || (size_t)n >= sizeof label) {
    /* truncated or error: handle it */
}

String Copy in Embedded C Programming

  • Fixed-size fields. Protocol structures often hold names in fixed arrays. Copy into them with a bounded function and set the last byte to zero explicitly.
  • Avoid dynamic allocation. Many firmware projects forbid malloc. Declare buffers statically with a documented maximum length and reject longer input.
  • memcpy for known lengths. After you validate the length, memcpy(dst, src, len + 1) copies the text plus terminator using the library’s fastest path, often DMA-assisted or word-wide.
  • Restrict overlap. strcpy and memcpy require that source and destination do not overlap. For overlapping regions, such as shifting text inside one buffer, use memmove.
  • Coding standards. Rules such as MISRA C restrict unbounded string functions. Learning the bounded patterns now makes later code reviews painless.

Common Mistakes When You Copy Strings in C

MistakeResultFix
Destination too smallBuffer overflowSize it for strlen(src) + 1 or use a bounded copy
Swapped argumentsTries to write to the source, possibly a literalRemember: destination first, like an assignment
Trusting strncpy to terminateUnterminated stringSet the last byte to zero, or use snprintf
Copying into an uninitialised pointerWild pointer writePoint the pointer at real storage first
Using strcpy on overlapping memoryUndefined behaviourUse memmove
Using sizeof on a pointer parameter as the limitLimit is 4 or 8Pass the buffer size explicitly

Best Practices

  • Carry a buffer size with every destination pointer you pass around.
  • When you copy strings in C in new code, prefer snprintf or strlcpy; keep strcpy for cases where you have already proven the length.
  • Validate external input length before copying it anywhere.
  • Compile with -Wall -Wextra and consider -D_FORTIFY_SOURCE=2 on hosted systems; the compiler caught both traps in this lecture.
  • Run a static analyser or sanitiser (-fsanitize=address) in your test builds to catch overflows early.

Key takeaways

  • strcpy copies the terminator and does not check the destination size.
  • The destination needs strlen(src) + 1 bytes.
  • Arrays cannot be assigned; literals cannot be modified.
  • strncpy does not guarantee a terminator; snprintf does.
  • Use memmove when regions can overlap.

Conclusion

The need to copy strings in C looks trivial, yet it is where most memory-safety bugs in C begin. You now know exactly what strcpy does, how to build it, and how to replace it with bounded, terminating alternatives. The final lecture of this section combines everything in a small command-line parser, with a quiz and interview questions to test yourself.

Frequently Asked Questions

Is strcpy deprecated or removed?

No. It is still part of standard C. It is just unsafe when you cannot prove the destination is large enough, so many coding standards discourage it.

Why can’t I write dst = src for two char arrays?

An array name is a constant address, not an assignable variable. Use strcpy, snprintf or memcpy to copy the contents.

Does strcpy copy the null terminator?

Yes. That is why the destination must have room for the length plus one byte.

What is the safest way to copy a string in C?

snprintf with the buffer size, or strlcpy where available. Both always terminate and let you detect truncation.

Why is strncpy considered dangerous?

It does not terminate the destination when the source fills the limit, and it pads short copies with zeros, which wastes time. It was designed for fixed-width record fields.

Can I use strcpy on a string literal destination?

No. Literals are read-only. Copy into a writable array instead.

Topics Covered

copy strings in Cstrcpystrncpysnprintfbuffer overflowmemcpyembedded C programmingfree embedded C course

Finish the Strings Chapter

Next: a hands-on command parser lab, a quiz and interview questions that tie strlen, strcmp and strcpy together. Stay with the free C programming course.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →