cdebugginggccdangling-pointer

Dangling pointer to pointer warning


gcc gives the following warning:

warning: storing the address of local variable 'node' in '*root_p' [-Wdangling-pointer=]

in this code:

treenode_t *nodeInsert(treenode_t ***root_p, int key){
    
    treenode_t *node = nodeCreate(key);

    if(*root_p == NULL){
        *root_p = &node;
        //*root_p = *root_p;
    }
    return node;
}

but if I uncomment *root_p = *root_p; it compiles without warnings.


Solution

  • Maybe it's easier to understand if we "draw" it out:

    First you have the variable node

    treenode_t *node;
    

    This is a local variable. Because I didn't initialize it (unlike your code) it looks like this:

    +------+
    | node | --> ???
    +------+
    

    It's a pointer, but it doesn't point anywhere valid.

    Then we assign to it:

    node = nodeCreate(key);
    

    And now it looks like this:

    +------+     +----------------+
    | node | --> | some memory... |
    +------+     +----------------+
    

    So far it's pretty straightforward.

    But then you use &node which gives you this:

    +-------+     +------+     +----------------+
    | &node | --> | node | --> | some memory... |
    +-------+     +------+     +----------------+
    

    Using this it is hopefully easier to see that &node points to the local variable node itself. And that variable in itself is not allocated on the heap.