Duplicate strings are passed to functions as parameters in C

I couldn't think of the correct title for my question, so this is it. I am trying to learn C and the following code is from the tutorial I am following.

struct Person {
    char *name;
    int age;
    int height;
    int weight;
};

struct Person *Person_create(char *name, int age, int height, int weight){
    struct Person *who = malloc(sizeof(struct Person));
    assert(who != NULL);

    who->name = strdup(name);
    who->age = age;
    who->height = height;
    who->weight = weight;

    return who;
}

void Person_destroy(struct Person *who){
    assert(who != NULL);

    free(who->name);
    free(who);
}

int main(int argc, char *argv[]){
    struct Person *joe = Person_create("Joe Alex", 32, 64, 140);

    ........

      

My question is in the function Person_create

, why are we duplicating name

into a new memory location for who->name

. Why can't we just make it who->name

point to the same location provided *name

provided by the function.
Also, if we have directly assigned an address *name

to who->name

, we must release it at Person_destroy

.

+3


source to share


2 answers


Why can't we just put who-> name in the same place as the name * given in the function.

For me, this one is who->name = strdup(name);

better than this who->name = name;

one if I know I will someday change the line given name

.

So, you can also do this:

who->name = name;

      



However, a string literal like this "Joe Alex"

is in read-only location, so if you want to do something like this (later in some part of your code):

who->name[3] = 'x';

      

you will get a segmentation fault. So if you want to change it, you would like malloc

some heap writable space that strdup

does for you.

You might want to take a look at: Changing a String Literal

+6


source


The char array is *name

not a dedicated array, which means that if you leave the scope of this function, this array is no longer used. Therefore the tutorial copies it to perform operations later on this variable. Moreover, if you directly assigned your variable *name

to who->name

, you shouldn't free it because it was not returned by malloc.



-2


source







All Articles