C strings need to be null terminated. Ie they need a '\0' character at the end, so common string expressions can tell where the string ends. String functions like strcpy and printf("%s... look for this null termination in their operation. When you do this:

for(i=0; s1[i] != '\0'; i++)
        s2[i] = s1[i];

You fail to copy the null terminator. This means when you print the string, printf will go through the string until it finds the first '\0' character somewhere after the end of your string. This is why you see the extra characters, and in the case where the NULL is outside your strings allotted memory you will actually cause undefined behaviour by accessing unallocated space, which is very very bad.

You either need to null terminate your string by adding:

s2[i] = '\0'

After your for loop. Or even better, use a standard c function strcpy.

Answer from Fantastic Mr Fox on Stack Overflow
๐ŸŒ
Programiz
programiz.com โ€บ c-programming โ€บ examples โ€บ string-copy
C Program to Copy String Without Using strcpy()
However, in this example, we will copy a string manually without using the strcpy() function. #include <stdio.h> int main() { char s1[100], s2[100], i; printf("Enter string s1: "); fgets(s1, sizeof(s1), stdin); for (i = 0; s1[i] != '\0'; ++i) { s2[i] = s1[i]; } s2[i] = '\0'; printf("String s2: %s", s2); return 0; }
Discussions

arrays - C - Copy a String without a library function - Stack Overflow
Find centralized, trusted content ... you use most. Learn more about Collectives ... Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I want to create a function that takes a string literal and an array and copies the characters of string literal to the array. Could you please inform me what is ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Implementing a string copy function in C - Stack Overflow
I looked at some other examples ... a null character to the destination string before exiting. However one thing I'm curious about is how memory is being handled. I noticed if I used the strcpy() library function, I could copy a string of 10 characters into a char array ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
C program copy string without using strcpy() with enough memory - Stack Overflow
I am trying to have this output: Comparing results of concat and strcat ... strcmp("Plain old stringTroy", "Plain old stringTroy") says: 0 The strcmp returns 0 if the two string arguments are iden... More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 25, 2017
Safest way to copy a string?
One option is snprintf(dest,n,โ€œ%sโ€,src), but this will likely be a little slower due to the time needed to parse the format string. More on reddit.com
๐ŸŒ r/C_Programming
79
55
May 7, 2023
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ safest way to copy a string?
r/C_Programming on Reddit: Safest way to copy a string?
May 7, 2023 -

I just fell foul of the fact that strncpy does not add an old terminator if the destination buffer is shorter than the source string. Is there a single function standard library replacement that I could drop in to the various places strncpy is used that would copy a null terminated string up to the length of the destination buffer, guaranteeing early (but correct) termination of the destination string, if the destination buffer is too short?

Edit:

  • Yes, I do need C-null terminated strings. This C API is called by something else that provides a buffer for me to copy into, with the expectation that itโ€™s null terminated

Edit 2:

  • I know I can write a helper function thatโ€™s shared across relevant parts of the code, but I donโ€™t want to do that because then each of those modules that need the function becomes coupled to a shared helper header file, which is fine in isolation but โ€œoh I want to use this code in another project, better make sure I take all the misc dependenciesโ€ is best avoided. Necessary if necessary, but if possible using a standard function, even better.

๐ŸŒ
Vultr
docs.vultr.com โ€บ clang โ€บ examples โ€บ copy-string-without-using-strcpy
C Program to Copy String Without Using strcpy() | Vultr Docs
December 4, 2024 - Use a loop to iterate through the source string, advancing the pointer until the null character is reached. Copy each character by dereferencing the source pointer and assigning it to the dereferenced destination pointer.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ c-program-copy-string-without-using-strcpy-function
C program to copy string without using strcpy() function - GeeksforGeeks
December 15, 2024 - Explanation: The most straightforward approach is to copy each character from the src string to the dest string using a loop. We continue copying characters until we encounter the null terminator ('\0'), which indicates the end of the string.
๐ŸŒ
CodeScracker
codescracker.com โ€บ c โ€บ program โ€บ c-program-copy-string.htm
C Program to Copy One String to Another
As you can see from the above snapshot, only "codes" are initialized in the variable str1, and the value of str1 gets copied to the str2 variable. Therefore, the above program is correct only when the user doesn't supply any strings with spaces. This program performs the same function as the previous one, but without the use of the library function strcpy():
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ c-program-to-copy-string-without-using-strcpy-function
C program to copy string without using strcpy() function
#include<stdio.h> main() { char str[50]; //create an empty string to store another string char *myString = "Program to copy a String"; sprintf(str, "%s", myString);//Use sprintf to copy string from myString to str printf("The String is: %s", str); }
Find elsewhere
Top answer
1 of 2
2

Your program has two bugs:

First

Your function CopyAString does not write a '\0' character to the end of the string. This means that the string s2[] does not have a '\0' character and you would not be able to pass s2[] to functions like printf() or other functions that expect an "input" string to end with '\0'.

However, in your program, this is not a problem because the for loop expects a fixed-length string.

Second

In your program, the following problem is more important:

You pass &str as first argument to CopyAString instead of str.

This means that s1 (the first argument of CopyAString) does not point to the character 'H' of "Hello world" but it points to the first byte of the value stored in the variable str...

Note that the variable str is a pointer: It does not store a "value" (here: the string "Hello world") but it stores an address of a value!

If the string "Hello world" is stored in the RAM at address 0x20 44 00 40 (this means: 0x40004420 on an x86 or ARM computer or 0x20440040 on a PowerPC), the variable str will contain the value 0x20 44 00 40.

s1[0] will be 0x20 (which is the space character). s1[1] will be 0x44 (which is 'D')...

2 of 2
0

For starters you should declare the function like

char * CopyAString( char *s1, const char *s2 );

similarly to the standard string function strcpy.

In this function call

CopyAString( &str1, s2 );

the expression &str1 has the type const char ** and yields the address of the pointer str1 but the function expects an argument expression of the type const char * that points to the first element of a string (the string literal).

Within the function you are not copying the terminating zero character

while (*p1 != '\0') {
    s2[index] = *p1;
    index++;
    p1++;
}

So the destination character array in general will not contain a string.

The function can be defined the following way

char * CopyAString( char *s1, const char *s2 )
{
    for ( char *p = s1; ( *p++ = *s2++ ); );

    return s1;
}

Within main instead of this for loop with the magic number 12 in the condition that invokes undefined behavior

for (int i = 0; i <= 12; i++){
    printf("%c", s2[i]);
}

it is better to write

for ( char *p = s2; *p != '\0'; ++p ){
    printf("%c", *p );
} 
putchar( '\n' );
๐ŸŒ
Tutorial Gateway
tutorialgateway.org โ€บ c-program-to-copy-string
C program to Copy String without using strcpy
April 4, 2025 - Please Enter any Sentence : Tutorial Gateway Copied into CopyStr = Tutorial Gateway Total Number of Characters that we copied = 17 ยท This program is the same as above. However, this time, we are using the Functions concept to separate the logic from the main. #include <stdio.h> #include <string.h> void CopyString(char str1[], char str2[], int index); int main() { char Str[100], CopyStr[100]; printf("\n Please Enter any text : "); gets(Str); CopyString(Str, CopyStr, 0); printf("\n Original = %s", Str); printf("\n Copied into CopyStr = %s", CopyStr); return 0; } void CopyString(char str1[], char str2[], int index) { str2[index] = str1[index]; if(str1[index] == '\0') { return; } CopyString(str1, str2, index + 1); }
๐ŸŒ
Log2Base2
log2base2.com โ€บ c-examples โ€บ string โ€บ string-copy.html
C program to copy string without using strcpy() function
Append null character '\0' at the end of a duplicate string. ... #include<stdio.h> int main() { char str[100],copy_str[100]; int i; scanf("%s",str); /* * Let's assume string as "abc" */ for(i = 0; str[i] != '\0'; i++) copy_str[i] = str[i]; /* * i = 0; copy_str[0] = str[0] i.e.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ strcpy-in-c
strcpy() in C - GeeksforGeeks
March 6, 2026 - In C, strcpy() is a built-in function used to copy one string into another. It is a part of the C standard strings library.
๐ŸŒ
Onlinegdb
learn.onlinegdb.com โ€บ c_program_copy_string_without_using_strcpy
C Program to copy string without using strcpy() | Learn Programming step by step
Problem Statement: Write a C Program to copy string without using strcpy() ยท Required Knowledge: C Input/Output, C Variables, C Datatypes, C for..loop
๐ŸŒ
W3Schools
w3schools.com โ€บ c โ€บ ref_string_strcpy.php
C string strcpy() Function
char str1[] = "Hello World!"; char str2[30]; strcpy(str2, str1); printf("%s\n", str1); printf("%s\n", str2); Try it Yourself ยป ยท The strcpy() function copies data from one string into the memory of another string.
๐ŸŒ
Cplusplus
cplusplus.com โ€บ reference โ€บ cstring โ€บ strcpy
strcpy - cstring
Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c++ โ€บ different-ways-to-copy-a-string-in-c-c
Different ways to copy a string in C/C++ - GeeksforGeeks
July 23, 2025 - The strndup() function is similar to strdup(), but it can copy at most n bytes. ... // C program to copy the string // using strndup function #include <stdio.h> #include <string.h> // Function to copy the string char* copyString(char s[]) { ...
๐ŸŒ
Code2master
code2master.com โ€บ c โ€บ c-program-copy-string-without-using-strcpy-function
Code2master.com
December 22, 2017 - The domain code2master.com may be for sale. Please click here to inquire
๐ŸŒ
Quora
quora.com โ€บ How-do-I-copy-a-string-in-C
How to copy a string in C - Quora
Answer (1 of 2): Three major ways. 1. strncpy [code]char* src = "a const string to be copied"; char dest[28] = {0}; char *strncpy(char *dest, const char *src, size_t n); dest[n]= '\0'; // terminate manually [/code] 1. strncpy copies a char array src into another char array dest up to a given ...
Top answer
1 of 2
2

There are multiple problems in your code:

  • The loop test in the length function is incorrect: instead of i < str[i], it should be:

     for (i = 0; str[i] != '\0'; i++)
    
  • the same problem in the concat function. Change the loop to:

     for (j = 0; src[j] != '\0'; j++) {
    
  • also in the concat function, i should be the length of dst, not that of src. You might use len instead of i for this variable.

  • The array str4 in function main does not have any space available at the end for concat to append anything. Define it with a larger size this way:

    char str4[MAXSIZE] = "Plain old string";      
    

Here is the corrected version:

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

#define MAXSIZE 32

void concat(char dest[], char src[]) {
    int len = length(dest);
    int j;
    for (j = 0; src[j] != '\0'; j++) {
        dest[len + j] = src[j];
    }
    dest[len + j] = '\0';
}

int length(char str[]) {
    int len = 0;
    int i;
    for (i = 0; i < str[i]; i++) {
        len++;
    }
    return len;
}

int main(void) {
    // Variable declarations for all parts
    char str2[MAXSIZE] = "Troy";
    char str4[MAXSIZE] = "Plain old string";
    char str6[MAXSIZE];
    // Part 6
    printf("\n----- Part 6 -----\n");
    // Make a copy of the destination string first, to be reused later
    strcpy(str6, str4);
    concat(str4, str2);
    strcat(str6, str2);
    printf("Comparing results of concat and strcat ...\n");
    printf("strcmp(\"%s\", \"%s\") says: %d\n",
           str4, str6, strcmp(str4, str6));
    return 0;
}
2 of 2
1

You have several problems in both functions:

concat

for(j; j<src[j] !='\0'; j++) {

What is the for exit condition here?, src[j] != '\0' is enough.

dest[i+j] = src[j];                                                       

Here you add data with an offset of i, but I is the length of src, not dst.

So the corrected function could be:

void concat(char dest[], char src[])
{
    /* descriptive variable name */
    int len_dst = length(dst);
    int j=0;

    /* clear exit condition */
    for(; src[j] != '\0'; j++) { 
      dest[len_dst+j] = src[j];
    }
    dest[len_dst+j] = '\0';
}

length

for(i=0;i<str[i];i++) {  

Same remark, what is this exit condition? src[i] != '\0' is enough

So the corrected function could be:

 int length(char str[])
 {
      int len=0;
      int i;
      /* clear exit condition */
      for ( i=0; str[i] != '\0'; i++) {
          len++;
      }
      return len;
 }

main

And warning in main function:

char str4[] = "Plain old string";
concat(str4, str2);  /* <- erases what is after str4 */

You do not have enough space to store result. Write something like:

char str2[] = "Troy";
char str4[MAXSIZE] = "Plain old string"; /* <-- reserve spaces after str4*/
/* ... */
concat(str4, str2);
๐ŸŒ
W3Schools
w3schools.com โ€บ cpp โ€บ ref_cstring_strcpy.asp
C++ cstring strcpy() Function
C++ Reference C++ Keywords C++ ... cout << str2 << "\n"; Try it Yourself ยป ยท The strcpy() function copies data from one C-style string into the memory of another string....