Echo Hao
Echo Hao

Reputation: 1

What happened to a pointer declared inside a function when the function returns

target is a copy of an existing pointer. If I don't set target to NULL before returning, will target be deleted such that the actual node target pointing to will be deleted as well?

typedef struct node *Node;

void make_curr_point_to_specific_list(List list, int id) {
    Node target = list->head;
    while (target != NULL) {
        if (id == target->id) {
            list->curr = target;
            // should i do "target = NULL;" before returning?
            return;
        }
        target = target->next;
    }
}

Upvotes: 0

Views: 30

Answers (1)

bruno
bruno

Reputation: 32586

If I don't set target to NULL before returning, will target be deleted such that the actual node target pointing to will be deleted as well?

no, there is no delete (in the meaning of free), just the area used in the stack for the parameters and local variable including target does not exit anymore after the function returned

There is a problem when you return (whatever the way) the address of a local variable and you dereference it while the variables disappeared

Remark : you use typedef to mask pointers, this is a bad idea, that makes you code unclear and facilitates the introduction of bugs

Upvotes: 3

Related Questions