How to Write Your Own strcat- C Programming Tutorials For Beginners

🚀 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 →

Write Your Own strcat

Chapter 9, Strings: implement string concatenation twice, once with array indexes and once with pointers, and discover why the return value must be the original address. Free embedded C course by EmbeddedPathashala.

If you want to truly understand strings, you should write your own strcat instead of only calling the library. In this lecture of our free C programming course you will build two working versions, trace them step by step, and see a common bug that returns the wrong pointer. These skills carry straight into embedded C programming, where firmware often ships its own tiny string helpers instead of linking a full library.

Topics in This Lecture

write your own strcat custom string functions in C free C programming course pointer arithmetic embedded C programming free C tutorial

What You Will Learn

  • The two-phase structure of every concatenation routine: find the end, then copy.
  • How to write the array-index version and the pointer version of the function.
  • Why the function must return the start of the destination and what goes wrong if it does not.
  • How nested calls evaluate and why they work on one shared buffer.
  • How to choose between the index style and the pointer style in real projects.

Prerequisites

You should have finished the previous two lectures on pointer-based copying and on the behaviour of the library strcat. You also need to be comfortable with while loops, character arrays and pointer increment.

The Two Phases of String Concatenation

Whatever style you choose, a concatenation function always does the same two jobs. In phase one it walks along the destination until it reaches the zero byte. In phase two it copies the source bytes from that position onwards and finishes by writing a fresh terminator. The only real choice is how you track the positions: with integer indexes or with moving pointers.

Two Phase Flow of a Custom strcat

Phase 1: advance through dst until the byte is zero
Phase 2: copy each byte of src to the current dst position
Finish: write the terminator after the last copied byte
Return: the address where dst started, not where it ended

Write Your Own strcat with Array Indexes

The index version is the easiest to read, so start there. Two integers, one for each string, march forward independently:

char *ep_strcat_idx(char dst[], const char src[])
{
    size_t i = 0, j = 0;

    while (dst[i] != '\0')      /* phase 1: find the end of dst */
        i++;

    while (src[j] != '\0') {    /* phase 2: append src */
        dst[i] = src[j];
        i++;
        j++;
    }
    dst[i] = '\0';              /* new terminator */
    return dst;                 /* original address, never moved */
}

Because dst itself is never changed, returning it is automatic. The type size_t is used for the indexes because it matches the size of any object in memory, including very large buffers.

Custom strcat Using Pointer Arithmetic

The pointer version moves the pointers themselves, so it needs a saved copy of the start. It reuses the copy idiom from the first lecture of this chapter:

char *ep_strcat_ptr(char *dst, const char *src)
{
    char *start = dst;

    while (*dst != '\0')                    /* phase 1 */
        dst++;

    while ((*dst++ = *src++) != '\0')       /* phase 2 */
        ;

    return start;
}

Phase two is exactly the compact copy loop. It copies the source terminator too, so no separate terminator line is needed.

FeatureIndex versionPointer version
Readability for beginnersVery clearNeeds idiom knowledge
Saved start pointerNot neededRequired for the return value
Typical generated codeSimilar after optimisationSimilar after optimisation
Best forTeaching and code reviewCompact helper functions

Complete Program: Chained Calls in Action

Because both functions return the destination, you can nest calls. The inner call runs first, appends its text, and hands the same buffer to the outer call. Save this as ep_chain.c with both functions above placed before main:

#include <stdio.h>

/* ep_strcat_idx and ep_strcat_ptr go here */

int main(void)
{
    char msg[40] = "spi";
    char alt[40] = "i2c";

    ep_strcat_ptr(ep_strcat_ptr(msg, "_flash"), "_driver");
    ep_strcat_idx(alt, "_bus");

    printf("%s\n", msg);
    printf("%s\n", alt);
    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o ep_chain ep_chain.c
$ ./ep_chain
spi_flash_driver
i2c_bus

Walk through the nested line carefully. First ep_strcat_ptr(msg, "_flash") turns msg into spi_flash and returns the address of msg. The outer call receives that address and appends _driver. Both buffers are 40 bytes, and the longest result needs 17, so there is plenty of room.

The Wrong Return Value Bug

A very common mistake is to return the pointer after it has moved. The code below looks reasonable and even builds the string correctly, but the value it returns is useless:

#include <stdio.h>

char *bad_strcat(char *dst, const char *src)
{
    while (*dst != '\0')
        dst++;
    while (*src != '\0')
        *dst++ = *src++;
    *dst = '\0';
    return dst;            /* BUG: points at the terminator */
}

int main(void)
{
    char buf[20] = "uart";
    char *r = bad_strcat(buf, "_rx");
    printf("buf      : [%s]\n", buf);
    printf("returned : [%s]\n", r);
    return 0;
}
$ ./ep_bad
buf      : [uart_rx]
returned : []

The buffer is correct, but the returned pointer addresses the terminator, so printing it gives an empty string. Any chained call built on it would append to the end of the text, which defeats the purpose. Always save the start and return it.

Tip: when you test a string helper, print both the buffer and the returned pointer. A mismatch exposes this bug immediately.

How to Test Your Own strcat

A string helper is small enough to test exhaustively by hand, so do it before you trust it. Build a short list of cases that target the places where terminator and boundary bugs hide, run each through your function and through the library function, and compare the two results with strcmp:

Test caseDestination beforeSourceExpected result
Empty source“abc”“”“abc”
Empty destination“”“xyz”“xyz”
Both empty“”“”“”
Single characters“a”“b”“ab”
Buffer exactly fullFits with one byte to spare for the terminatorAny textCorrect string, terminator inside the buffer

Surround the destination with a few guard bytes in a test build, and check afterwards that the guards are unchanged. If a guard byte changes, your function wrote outside the buffer.

Real-World Use Cases

  • Bootloaders and small RTOS projects that cannot afford the full C library.
  • Safety-oriented codebases that wrap every string operation with extra checks.
  • Unit-test helpers that compare your implementation against the library one for many random inputs.
  • Interview coding rounds, where writing a string function from scratch is a standard question.

Common Mistakes and Troubleshooting

Warning: the custom versions share the same danger as the library function. Neither one checks the destination size.

  • Missing terminator. If you stop the copy loop before writing the zero, the result is not a string.
  • Returning the moved pointer. Shown above. Save the start first.
  • Modifying the source. Declare the source as const so the compiler rejects accidental writes.
  • Overlapping arguments. Calling the function with the same buffer as source and destination loops forever, because the terminator keeps moving away.

Best Practices, Performance and Security

Add a capacity parameter when you write helpers for real firmware. A version such as ep_strcat_safe(dst, cap, src) can check that the combined length fits and return an error code, which fits the defensive style of embedded C programming. For performance, avoid chains of many small appends on long buffers, because each one repeats the scan for the end. For security, never use these unbounded versions on text from the outside world, such as network packets or user input. Test every helper with empty strings, one-character strings and strings that exactly fill the buffer, since these edge cases are where terminator bugs hide.

Summary and Key Takeaways

  • Every concatenation routine has two phases: seek the end of the destination, then copy the source with its terminator.
  • The index version is readable, and the pointer version is compact.
  • Return the original destination address so calls can be nested.
  • Returning the moved pointer is a classic bug that gives an empty or wrong result.
  • Custom helpers need the same capacity discipline as library functions.

Conclusion

When you write your own strcat, the library stops being magic. You have seen that it is a seek loop followed by a copy loop, and you have seen how one small decision about the return value changes whether chaining works. Understanding these mechanics gives you confidence to review other people’s string code and to spot overflow risks early. In the next lecture you will compare strings stored as arrays with strings reached through pointers, which explains many surprising behaviours you may have already noticed.

Frequently Asked Questions

Why write my own strcat when the library has one?

Writing it teaches how strings, pointers and terminators interact. It also prepares you for interviews and for projects that provide their own minimal string helpers.

Which version is better, index or pointer?

Both compile to similar machine code with optimisation enabled. Choose the index version for clarity and the pointer version for compact helper code.

Why must the function return the start of the destination?

It lets callers nest calls and use the result directly. A pointer to the end of the text cannot be used as the string.

How do nested strcat calls evaluate?

The innermost call runs first and returns the buffer address, which becomes the destination argument of the next call outward.

How can I make a custom strcat safe?

Pass the buffer capacity, compute the combined length, and return an error code when it does not fit instead of writing past the end.

Practise With the Free C Programming Course

Type both versions yourself, break them on purpose, and compare with the library. That is the fastest way to master C programming for embedded systems.

💬 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 →