What is a safe way to concatenate strings in C?

I need to build a file path from two lines. I could use this (but not tested):

/* DON'T USE THIS CODE! */
/* cmp means component */
char *path_cmp1 = "/Users/john/";
char *path_cmp2 = "foo/bar.txt";
unsigned len = strlen(path_cmp1);
char *path = path_cmp1;
for (int i = 0; i < strlen(path_cmp2); i++) {
  path[len + i] = path_cmp2[i];
}

but it can lead to memory corruption, I think. Is there a better way to do this, or is there a function for this in the standard library?

+5
source share
9 answers
#include <stdlib.h>
#include <string.h>

char *join(const char* s1, const char* s2)
{
    char* result = malloc(strlen(s1) + strlen(s2) + 1);

    if (result) // thanks @pmg
    {
        strcpy(result, s1);
        strcat(result, s2);
    }

    return result;
}

It is simple enough to be written in place, especially when you have multiple lines to concatenate.

Note that these functions return their target argument, so you can write

char* result = malloc(strlen(s1) + strlen(s2) + 1);
assert(result);
strcat(strcpy(result, s1), s2);

but it is less readable.

+9
source
#include <stdio.h> 

char *a = "hello ";
char *b = "goodbye";
char *joined;

asprintf(&joined, "%s%s", a, b)
+5
source

strcat strncat.

+3
char *path_cmp1 = "/Users/john/";
char *path_cmp2 = "foo/bar.txt";

int firstLength = strlen(path_cmp1);
int secondLength = strlen(path_cmp2);
char *both = malloc(firstLength+secondLength+1);
memcpy(both, path_cmp1, firstLength);
memcpy(both+firstLength, path_cmp2, secondLength+1);
       // this +1 copyes the second string null-terminator too.
+3

: 1 - strlen for , , .

2 - strlen strlen (path_cmp1) , .

, , :

char *join_strings(const char* s1, const char* s2)
{
    size_t lens1 = strlen(s1);
    size_t lens2 = strlen(s2);

    //plus 1 for \0
    char *result = malloc(lens1 + lens2 + 1);

    if(result)
    {
        memcpy(result, s1, lens1);
        memcpy(result+lens1, s2, lens2+1);
    }

    //do not forget to call free when do not need it anymore
    return result;
}
+3

strcpy/strcat .

+2

strcat. ( , .)

+2

strcat string.h?

+2

pathis just a pointer to path_cmp1, and you are trying to access the end of the array. Very rarely, this will work, but in the vast majority of cases, you will damage memory.

As others have indicated, use strcatto concatenate strings.

+2
source

All Articles