Search code examples
carraysmemcpystrcpystrncpy

C copy char * to char[]


Hello I am trying to copy a char * pointer to a char [] array.

this is my code so far

char * string_add(char * base, char * toAdd)
{
    char * string=malloc(strlen(base)+streln(toAdd)+1);
    sprintf(string,"%s%s",base,toAdd);
    char returnString[strlen(string)+1]; 
    // here comes my problem:
    memcpy(returnString,string,strlen(string)+1);
    // want to add free(string) here
    return returnString;
}

I want to use such a function to save code. I don't want to look after every allocated memory. I also tried

memcpy(&returnString,string,strlen(string)+1);

and some variants with strcpy and strncpy. But following problem persists:

if I call the function twice like:

int main(int argc, char * argv[])
{
    char * str1=string_add(argv[1],"-test1"); 
    char * str2=string_add(argv[1],"-test2"); 
    printf("%s, %s", str1,str2);
}

the output is like:

abc-test2, abc-test2

How can I realize this?

Thank you in advance!


Solution

  • in C, you have to look after the malloced memory, the char array you are declaring is on the stack, and will be gone after the function returns, only the malloc memory will hang around. and Yes, you will have to look after it and clean it up.