Search code examples
cdangling-pointer

Is this a dangling pointer?


int main(int argc, char *argv[]) {

    int x[3] = {1, 2, 3}; //create an array x

    int *y = x; //create pointer y and let it point to the array x

    *y = null; //now x points to the null, therefore x is a dangling pointer

}

I am a little bit confused here, since the value that x points to is null, is x a dangling pointer?


Solution

  • x is an array declared like

    int x[3] = {1, 2, 3};
    

    So it can not be a dangling pointer. Objects of array types are not pointers.

    In this declaration

    int *y = x;
    

    the array designator x used as an initializing expression is implicitly converted to a pointer to its first element and this pointer is not an lvalue. After this declaration the initializing expression will not be alive.

    So there is no dangling pointer in the presented program.

    Pay attention to that this statement

    *y = null;
    

    is invalid. It seems you mean

    y = NULL;
    

    Now the variable y is a null pointer.

    Here is an example of a dangling pointer.

    int *p = malloc( sizeof( *p ) );
    free( p );
    

    After the call of free the pointer p is a dangling pointer. It does not point to a valid object.