Search code examples
csubstringc-stringsfunction-definition

char* change when applying a function


I am trying to implement a function which transform a char* of the form [name] into name. Here is my function :

char* rmChar (char* tagName){
    char* newName = tagName;
    newName++; //remove first character
    unsigned long len = strlen(newName)-1;

    if (newName[len] == '\n'){
        newName[len] = 0;
        newName[len-1] = 0;
    }
    else{
        newName[len] = 0;
    }

    return newName;
}

What I don't understand is that if I apply my function on a variable of type char* it will modify it. For example if I run the following code :

char test[] =  "[test]";
printf("%s", rmChar(test));
printf("%s", test);

then it prints out : test[test

I don't understand why the variable has been change into [test ? is there a way to modify my function rmChar such that the variable test is unchanged ?

Thank you !


Solution

  • By passing char*, you are passing the place that the string exists, not the string itself. Therefore, modifying the string will modify the original string.

    To avoid this, you can copy string before modifying.

    example fix:

    #include <stdlib.h> /* for using malloc() and free() */
    
    char* rmChar (char* tagName){
        /* copy input string */
        static char* copiedStr = NULL;
        free(copiedStr);
        copiedStr = malloc(strlen(tagName)+1);
        strcpy(copiedStr, tagName);
        /* and edit it */
        char* newName = copiedStr;
        newName++; //remove first character
        unsigned long len = strlen(newName)-1;
    
        if (newName[len] == '\n'){
            newName[len] = 0;
            newName[len-1] = 0;
        }
        else{
            newName[len] = 0;
        }
    
        return newName;
    }
    

    This function allows throwing returned pointer away like printf("%s", rmChar(test)); with minimum memory leak, but is not safe when it is used from multiple threads.