Home > Back-end >  Can't change string given to function
Can't change string given to function

Time:01-09

Once again, I have stumbled across another unexpected occurrence.

In the following code, it seems that if I use changeStr() to change a string, from the function's perspective it has changed, but it has not changed from the program's perspective.

However if I don't use changeStr() and set the string myself, it seems to work.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* set string to newStr */
void changeStr(char *string, char *newStr) {
    string = realloc(string, strlen(newStr)   1);
    memcpy(string, newStr, strlen(newStr)   1);
    printf("String from function=%s\n", string);
}

int main() {
    char *str = NULL;
    changeStr(str, "Hello world!");
    printf("String=%s\n", str);

    /* set string without function */
    char *test = NULL;
    char *newStr = "hello world";
    test = realloc(test, strlen(newStr)   1);
    memcpy(test, newStr, strlen(newStr)   1);
    printf("NewStr=%s\n", test);

    free(str);
    free(test);

    return 0;
}

Output:

String from function=Hello world!
String=(null)
NewStr=hello world

I know that function parameters in C are duplicated into a new variable for the function, but only the pointer is duplicated - not the string itself - so what's going on here?

P.S. I am no multi-year experienced programmer, so not sure if something is wrong.

CodePudding user response:

The realloc() call as you are using it creates a new object and returns the pointer to it, which gets assigned into the string local variable in changeStr().

If you want the caller function (main()) to have access to that newly allocated object, then the callee function (changeStr()) needs to pass the new pointer back to the caller (e.g. as a return value). For example:

char *changeStr(char *string, char *newStr) {
    string = realloc(string, strlen(newStr)   1);
    memcpy(string, newStr, strlen(newStr)   1);
    printf("String from function=%s\n", string);
    return string;  // <-- return the updated string object to caller
}

int main() {
    char *str = NULL;
    str = changeStr(str, "Hello world!");
    printf("String=%s\n", str);
  • Related