Search code examples
cscopefree

Free after assigning value for field in global structure


Here is small C program that I am trying to understand:

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

typedef struct dm_user_params_t {
    int x;
} dm_user_params;

dm_user_params xx;

void set_user_params(dm_user_params *yy) {
    xx.x = yy->x;
}

int main() {
    dm_user_params xx;
    dm_user_params *yy;
    yy = malloc(sizeof(dm_user_params));
    yy->x = 217;
    set_user_params(yy);
    free(yy);
    printf("2 %d" , xx.x);
    return 0;
}

Output:

537340672

What should I do, so that value in xx.x should persist ?

Is reference is copied instead of value when I do xx.x = yy->x ? How to verify this ?


Solution

  • Your local variable xx is shadowing the global identical declaration (bearing the exact type & name)

    set_user_params changes the global xx

    Fix 1: remove the local variable. Also:

    void set_user_params(dm_user_params *yy) {
        xx.x = yy->x;
    }
    

    could be written:

    void set_user_params(const dm_user_params *yy) {
        xx = *yy;
    }
    

    so when you add more fields the set_user_params doesn't need to be updated.

    Fix 2: remove the global variable and change prototype as is:

    void set_user_params(dm_user_params *dest, const dm_user_params *src) {
        *dest= *src;
    }
    

    then call like this set_user_params(&xx,yy);