cpointersmallocfree

How to free the value inside struct in c


I don't know how to reset the value field inside the Hello struct. It's a pointer pointed to an outside passed input argument.

typedef struct Hello {
    void *value;
} Hello;

Hello* create_hello() {
    Hello* hello = malloc(sizeof(Hello));
    hello->value = NULL;
    return hello;
}

set_value(Hello *hello, void *value) {
    hello->value = value;
}

void free_hello(Hello *hello) {
    /** Should I set the value to NULL before freeing the hello? */
    hello->value = NULL;
    
    /** Free the hello */
    free(hello);
    
    /** Set hello to NULL inside the free_hello()? */
    hello = NULL;
}

Here is the test_function:

test_function(void* value) {
    Hello *hello = create_hello();
    set_value(hello, value);
    
    free_hello(hello);
    
    /** Set hello to NULL inside the test_function()? */
    hello = NULL;
}
  1. Should I execute hello->value = NULL; inside the free_hello in order to reset the hello->value to the default NULL status?

  2. Should I execute hello = NULL; inside the free_hello() or test_function() after freeing the struct with free()?


Solution

  • Should I call hello->value = NULL; inside the free_hello in order to reset the hello->value to the default NULL status?

    There's no need because you call free(hello) on the next line, so the pointer value becomes indeterminate, effectively meaning you shouldn't read it.

    Should I call hello = NULL; inside the free_hello() or test_function() after freeing the struct with free()?

    Setting hello to NULL inside of free_hello has no effect because it's a local variable to the function. Whether you do so with the variable from the calling function depends on what you intend to do with it later, but is typically a good idea so you don't have a freed pointer dangling around.