ImbaBalboa
ImbaBalboa

Reputation: 867

Free a variable malloc and return in a function in c?

I have a linked list of users, thus I have done this function which delete a user from the linked list :

puser* delete_user(puser* list_users, int fd_to_delete) {

puser *save_users;
save_users = (puser *)malloc(sizeof(puser));
save_users = list_users;
int nb_users = 0;

nb_users = count_user(list_users);

// only one user
if(nb_users == 1)
    free(list_users);
    return NULL;

// several users
if(nb_users > 0) {

    // if it's the first user of the list
    if(user_get_fd(list_users) == fd_to_delete)
        return user_get_next_one(list_users);

    // else 
    while(list_users != NULL) {

        if(user_get_next_one(list_users) != NULL) {

            if(user_get_fd(user_get_next_one(list_users)) == fd_to_delete)
                list_users->next_client = user_get_next_one(user_get_next_one(list_users));
        }
    list_users = user_get_next_one(list_users);
    }

    return save_users;
}
return save_users;}

I have malloc "save_users", but I need to return this value. My question is how to free this variable ?

Thank you

Upvotes: 0

Views: 346

Answers (2)

fpes
fpes

Reputation: 974

If you want to keep this the way it is, you can decide not to return a puser*.

Instead you can pass a puser**, pointing to the location of puser*list_user. You can then dereference this puser** in this line:

save_users = *list_users;

At the end of your function, you can free(*list_user), set *list_user = save_users.

So:

puser * list_user ...;
delete_user(&list_user, ...);

Where delete_user is now:

void delete_user(puser** list_user, ...){
    puser * saved_user = malloc(...);
    saved_user = *list_user;
     ... Do stuff to saved user ...
    free(*list_user);
    *list_user = saved_user;
}

Now, when your function exits, list_user is now pointing to the saved_user you allocated in the function. You no longer need to free saved_user. You free the old list_user instead.

Obviously free must be a function that can free your data structure.

Upvotes: 0

kcraigie
kcraigie

Reputation: 1262

you could just call free(), but it would be better practice to provide another function into your api called something like free_save_users() and call free() in this function, in case you ever need to change how the memory gets allocated.

Upvotes: 1

Related Questions