Search code examples
cstringfunctionpointers

Concatenation of 2 strings and a new pointer returned


I am not sure if I was dreaming or not because I can not find this function anywhere I look. The function calls for 2 strings to concat, then would return the pointer to a newly allocated memory block with the 2 strings fused.

Does anyone know of such a function?


Solution

  • I am not aware of anything like that in the C standard; POSIX C contains strdup which returns a newly allocated copy of the provided string, but that's not what you are asking.

    Still, you can easily build it by yourself:

    char * strcat_alloc(const char * first, const char * second)
    {
        size_t s1=strlen(first), s2=strlen(second), stot=s1+s2+1;
        // Length overflow check (see @R.. comment)
        if(stot<s2+1)
            return NULL;
        char * ret = malloc(stot);
        if(ret==NULL)
            return NULL;
        strcpy(ret,first);
        strcpy(ret+s1, second);
        return ret;
    }