Search code examples
ccopydynamic-memory-allocationc-stringsfunction-definition

Copy one string into another


When the below piece of the code is run it is giving some kind of seg fault and program is crashing. So initially temp = "abcdef" and finally temp3 should also contain "abcdef"

My intention is to copy the content of "temp" into
 "temp3".Please suggest where I am doing wrong.

void fun (char * input , char **input1) {

size_t size = strlen(input);
*input1 = (char **) malloc(sizeof(char) * (size+1));
memcpy(*input1 , input , size);
}

int main(){

char * temp = "abcdef";
char * temp3;

fun(temp , temp3);
printf("%s",temp3);

return 0;
}


Solution

  • For starters the second argument of the function

    void fun (char * input , char **input1) {
    

    has the type char ** while you are passing an expression of the type char *.

    char * temp3;
    
    fun(temp , temp3);
    

    So already the program has undefined behavior. You need to call the function like

    fun(temp , &temp3);
    

    Within the function you have to write at least the following

    size_t size = strlen(input) + 1;
    *input1 = malloc(sizeof(char) * size);
    memcpy( *input1 , input , size);
    

    That is you need to count the terminating zero character '\0' of the source string.

    And the first parameter of the function should have the qualifier const

    void fun ( const char * input , char **input1);
    

    In the end of the program you should free the allocated memory in the function

    free( temp3 );
    

    It would be more safer to check whether the memory was allocated successfully. For example

    void fun( const char * input , char **input1 )
    {
        size_t size = strlen(input) + 1;
        *input1 = malloc(sizeof(char) * size);
    
        if ( *input1 ) memcpy( *input1 , input , size);
    }
    

    and in main you could write

    fun(temp , &temp3);
    if ( temp3 ) puts( temp3 );
    
    free( temp3 );