dangling pointers

This is a discussion on dangling pointers within the C Programming forums, part of the General Programming Boards category; Could anyone explain dangling pointers with better programs....

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    12

    dangling pointers

    Could anyone explain dangling pointers with better programs.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,529
    p = malloc( 10 );
    free( p );
    // p is now a dangly
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Aug 2005
    Posts
    12
    what actually happens here

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    If you don't try using p again without allocating more space, or pointing it at something valid, nothing. If you do try using it without allocating more space, or pointing it at something valid, BadThings(TM) happen.


    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,282
    The scenario is that the pointer initially points at an object. The object ceases to exist, but the value of the pointer does not change. The pointer is "dangling" because it points at an object that no longer exists.

    In the example given by salem, the call to free() causes the block of memory pointed at by p to be released. The call to free(p), however, does not change the value of p.

    another example is

    Code:
    int *func()
    {
        int x;
        x = 42;
        return &x;   /*   x ceases to exist when function returns */
    }
    
    int main()
    {
       int *y = func();
       *y = 100;  /* y is a dangling reference, so this line yields undefined behaviour */
    }
    Last edited by grumpy; 08-30-2005 at 06:27 AM.

  6. #6
    Registered User
    Join Date
    Aug 2005
    Posts
    12
    thanks a lot

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Using pointers to pointers
    By steve1_rm in forum C Programming
    Replies: 18
    Last Post: 05-29-2008, 05:59 AM
  2. vector destruction question
    By dudeomanodude in forum C++ Programming
    Replies: 4
    Last Post: 04-04-2008, 01:20 PM
  3. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM
  4. Staticly Bound Member Function Pointers
    By Polymorphic OOP in forum C++ Programming
    Replies: 29
    Last Post: 11-28-2002, 12:18 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21