Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't change string given to function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading