You could use strdup() to return a copy of a C-string, as in:

#include <string.h>

const char *stringA = "foo";
char *stringB = NULL;

stringB = strdup(stringA);
/* ... */
free(stringB);
stringB = NULL; 

You could also use strcpy(), but you need to allocate space first, which isn't hard to do but can lead to an overflow error, if not done correctly:

#include <string.h>

const char *stringA = "foo";
char *stringB = NULL;

/* you must add one to cover the byte needed for the terminating null character */
stringB = (char *) malloc( strlen(stringA) + 1 ); 
strcpy( stringB, stringA );
/* ... */
free(stringB);
stringB = NULL;

If you cannot use strdup(), I would recommend the use of strncpy() instead of strcpy(). The strncpy() function copies up to — and only up to — n bytes, which helps avoid overflow errors. If strlen(stringA) + 1 > n, however, you would need to terminate stringB, yourself. But, generally, you'll know what sizes you need for things:

#include <string.h>

const char *stringA = "foo";
char *stringB = NULL;

/* you must add one to cover the byte needed for the terminating null character */
stringB = (char *) malloc( strlen(stringA) + 1 ); 
strncpy( stringB, stringA, strlen(stringA) + 1 );
/* ... */
free(stringB);
stringB = NULL;

I think strdup() is cleaner, myself, so I try to use it where working with strings exclusively. I don't know if there are serious downsides to the POSIX/non-POSIX approach, performance-wise, but I am not a C or C++ expert.

Note that I cast the result of malloc() to char *. This is because your question is tagged as a c++ question. In C++, it is required to cast the result from malloc(). In C, however, you would not cast this.

EDIT

There you go, there's one complication: strdup() is not in C or C++. So use strcpy() or strncp() with a pre-sized array or a malloc-ed pointer. It's a good habit to use strncp() instead of strcpy(), wherever you might use that function. It will help reduce the potential for errors.

Answer from Alex Reynolds on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › c language › strcpy-in-c
strcpy() in C - GeeksforGeeks
March 6, 2026 - It is a part of the C standard strings library. The strcpy function in C is used to copy a string, with syntax: strcpy(dest, src);, where dest is the destination array and src is the source string.
🌐
Programiz
programiz.com › c-programming › library-function › string.h › strcpy
C strcpy() - C Standard Library
The strcpy() function also returns the copied string. The strcpy() function is defined in the string.h header file. #include <stdio.h> #include <string.h> int main() { char str1[20] = "C programming"; char str2[20]; // copying str1 to str2 strcpy(str2, str1); puts(str2); // C programming return 0; }
Discussions

Copy string in C
A high-level, general-purpose ... features in addition to facilities for low-level memory manipulation. ... A C string is a nul-terminated character array. The C language does not allow assigning the contents of an array to another array. As noted by Barry, you must copy the individual ... More on learn.microsoft.com
🌐 learn.microsoft.com
3
0
September 12, 2020
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
c - How to copy a string using a pointer - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Here's a program I wrote to copy a string constant. More on stackoverflow.com
🌐 stackoverflow.com
How does the STL string library handle copying C strings into an std::string?
How are you making a std::string from value? The only safe ways are the constructors that communicate the size of, or the end of, the string std::string w{std::begin(value), std::end(value)}; std::string w{value,4}; (and trivial variants) More on reddit.com
🌐 r/Cplusplus
8
5
July 13, 2022
Top answer
1 of 4
30

You could use strdup() to return a copy of a C-string, as in:

#include <string.h>

const char *stringA = "foo";
char *stringB = NULL;

stringB = strdup(stringA);
/* ... */
free(stringB);
stringB = NULL; 

You could also use strcpy(), but you need to allocate space first, which isn't hard to do but can lead to an overflow error, if not done correctly:

#include <string.h>

const char *stringA = "foo";
char *stringB = NULL;

/* you must add one to cover the byte needed for the terminating null character */
stringB = (char *) malloc( strlen(stringA) + 1 ); 
strcpy( stringB, stringA );
/* ... */
free(stringB);
stringB = NULL;

If you cannot use strdup(), I would recommend the use of strncpy() instead of strcpy(). The strncpy() function copies up to — and only up to — n bytes, which helps avoid overflow errors. If strlen(stringA) + 1 > n, however, you would need to terminate stringB, yourself. But, generally, you'll know what sizes you need for things:

#include <string.h>

const char *stringA = "foo";
char *stringB = NULL;

/* you must add one to cover the byte needed for the terminating null character */
stringB = (char *) malloc( strlen(stringA) + 1 ); 
strncpy( stringB, stringA, strlen(stringA) + 1 );
/* ... */
free(stringB);
stringB = NULL;

I think strdup() is cleaner, myself, so I try to use it where working with strings exclusively. I don't know if there are serious downsides to the POSIX/non-POSIX approach, performance-wise, but I am not a C or C++ expert.

Note that I cast the result of malloc() to char *. This is because your question is tagged as a c++ question. In C++, it is required to cast the result from malloc(). In C, however, you would not cast this.

EDIT

There you go, there's one complication: strdup() is not in C or C++. So use strcpy() or strncp() with a pre-sized array or a malloc-ed pointer. It's a good habit to use strncp() instead of strcpy(), wherever you might use that function. It will help reduce the potential for errors.

2 of 4
4

If I just initialize stringB as char *stringB[23], because I know I'll never have a string longer than 22 characters (and allowing for the null terminator), is that the right way?

Almost. In C, if you know for sure that the string will never be too long:

char stringB[MAX+1];
assert(strlen(stringA) <= MAX));
strcpy(stringB, stringA);

or, if there's a possibility that the string might be too long:

char stringB[MAX+1];
strncpy(stringB, stringA, MAX+1);
if (stringB[MAX] != '\0') {
    // ERROR: stringA was too long.
    stringB[MAX] = '\0'; // if you want to use the truncated string
}

In C++, you should use std::string, unless you've proved that the overhead is prohibitive. Many implementations have a "short string optimisation", which will avoid dynamic allocation for short strings; in that case, there will be little or no overhead over using a C-style array. Access to individual characters is just as convenient as with a C-style array; in both cases, s[i] gives the character at position i as an lvalue. Copying becomes stringB = stringA; with no danger of undefined behaviour.

If you really do find that std::string is unusable, consider std::array<char,MAX+1>: a copyable class containing a fixed-size array.

If stringB is checked for equality with other C-strings, will the extra space affect anything?

If you use strcmp, then it will stop at the end of the shortest string, and will not be affected by the extra space.

🌐
W3Schools
w3schools.com › c › ref_string_strcpy.php
C string strcpy() Function
C Examples C Real-Life Examples ... str1); printf("%s\n", str2); Try it Yourself » · The strcpy() function copies data from one string into the memory of another string....
🌐
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 - We can use the inbuilt function strcpy() from <string.h> header file to copy one string to the other.
🌐
C For Dummies
c-for-dummies.com › blog
To Copy or to Duplicate a String | C For Dummies Blog
December 26, 2015 - The destination’s allocated space must be of the same size (or larger) than the source. The value returned is a pointer to the dst string. The strcpy() function duplicates string scr to the location specified by dst one character at a time until and including the null character, \0.
Find elsewhere
🌐
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).
🌐
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 ...
🌐
Programiz
programiz.com › c-programming › examples › string-copy
C Program to Copy String Without Using strcpy()
#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; } ... Enter string s1: Hey fellow programmer. String s2: Hey fellow programmer. The above program copies the content of string s1 to string s2 manually.
🌐
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.

🌐
TechOnTheNet
techonthenet.com › c_language › standard_library_functions › string_h › strcpy.php
C Language: strcpy function (String Copy)
In the C Programming Language, the strcpy function copies the string pointed to by s2 into the object pointed to by s1. It returns a pointer to the destination.
🌐
Educative
educative.io › answers › how-to-copy-a-string-using-strcpy-function-in-c
How to copy a string using strcpy() function in C
strcpy() takes two strings as arguments and character by character (including \0) copies the content of string Src to string Dest, character by character.
🌐
CodeScracker
codescracker.com › c › program › c-program-copy-string.htm
C Program to Copy One String to Another
To copy a string in C programming, you have to ask the user to enter the string to store it in the first string variable, say str1, and then copy it into the second string variable, say str2, using the strcpy() function of the string.h library. The function strcpy() takes two arguments.
🌐
DEV Community
dev.to › sjmulder › string-copy-in-c-38k9
String copy in C - DEV Community
August 12, 2023 - Instead, use strcpy_s() if available, strclpy(), or even snprintf() (snprintf(dst, sizeof(dst), "%s", src)). ... void strcpy_1(char *src, char *dst) { size_t len, i; len = strlen(src); for (i=0; i < len; i++) dst[i] = src[i]; dst[len] = '\0'; ...
🌐
W3Schools
w3schools.in › c-programming › examples › copy-string
C Program to Copy String Using strcpy - W3Schools
This C program is used to copy the string by using the library function strcpy(). ... #include<stdio.h> #include<string.h> main() { char source[] = "C Program"; char destination[50]; strcpy(destination, source); printf("Source string: %s\n", source); printf("Destination string: %s\n", destination); ...
🌐
Cplusplus
cplusplus.com › reference › string › string › copy
std::string::copy
Copies a substring of the current value of the string object into the array pointed by s. This substring contains the len characters that start at position pos.
🌐
Sternum IoT
sternumiot.com › home › strcpy and strncpy c functions – syntax, examples, and security best practices
strcpy and strncpy C Functions | Syntax, Examples & Security Best Practices | Sternum IoT
January 30, 2024 - It is included in the string.h header file and stands for “string copy.” The primary objective of this function is to replicate a source string into a destination buffer while ensuring both strings are null-terminated. The strcpy() function ...
Top answer
1 of 7
21

To copy strings in C, you can use strcpy. Here is an example:

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

const char * my_str = "Content";
char * my_copy;
my_copy = malloc(sizeof(char) * (strlen(my_str) + 1));
strcpy(my_copy,my_str);

If you want to avoid accidental buffer overflows, use strncpy instead of strcpy. For example:

const char * my_str = "Content";
const size_t len_my_str = strlen(my_str) + 1;
char * my_copy = malloc(len_my_str);
strncpy(my_copy, my_str, len_my_str);
2 of 7
17

To perform such manual copy:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char* orig_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char* ptr = orig_str;

    // Memory layout for orig_str:
    // ------------------------------------------------------------------------
    // |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|  --> indices
    // ------------------------------------------------------------------------
    // |A|B|C|D|E|F|G|H|I|J|K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z |\0|  --> data
    // ------------------------------------------------------------------------

    int orig_str_size = 0;
    char* bkup_copy = NULL;

    // Count the number of characters in the original string
    while (*ptr++ != '\0')
        orig_str_size++;        

    printf("Size of the original string: %d\n", orig_str_size);

    /* Dynamically allocate space for the backup copy */ 

    // Why orig_str_size plus 1? We add +1 to account for the mandatory 
    // '\0' at the end of the string.
    bkup_copy = (char*) malloc((orig_str_size+1) * sizeof(char));

    // Place the '\0' character at the end of the backup string.
    bkup_copy[orig_str_size] = '\0'; 

    // Current memory layout for bkup_copy:
    // ------------------------------------------------------------------------
    // |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|  --> indices
    // ------------------------------------------------------------------------
    // | | | | | | | | | | |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |\0|  --> data
    // ------------------------------------------------------------------------

    /* Finally, copy the characters from one string to the other */ 

    // Remember to reset the helper pointer so it points to the beginning 
    // of the original string!
    ptr = &orig_str[0]; 
    int idx = 0;
    while (*ptr != '\0')
        bkup_copy[idx++] = *ptr++;

    printf("Original String: %s\n", orig_str);   
    printf("Backup String: %s\n", bkup_copy);

    return 0;
}
🌐
Vultr
docs.vultr.com › clang › examples › copy-string-without-using-strcpy
C Program to Copy String Without Using strcpy() | Vultr Docs
December 4, 2024 - Initialize the source string and an empty destination string. 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 ...