Search code examples
cpointersmemory-leaksdangling-pointer

Dangling pointer example confusion


Why isn't the following example correct? Why doesn't it demonstrate a dangling pointer? My teacher said it doesn't show the dangling pointer. Thanks in advance!

int X = 32;
int *p = &X;
free(p);
*p = 32; //<------Shouldn't this line cause dangling pointer ???

Same thing here. Why doesn't the following example demonstrate a memory leak?

void function(int x){
   int *p = &x;
   *p = 32;
   //shouln't this code show a warning as p was not freed?
}

Solution

  • To cite Wikipedia:

    Dangling pointer and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type.

    Also you should only free memory which was allocated by malloc or similar allocation functions -it seems that is your confusion in both cases. Basically none of your examples need free.

    An example of dangling pointer would be:

    {
       char *ptr = NULL;
    
       {
           char c;
           ptr = &c;
       } 
         // c falls out of scope 
         // ptr is now a dangling pointer 
    }
    

    Also if you had example like:

    int *p = malloc(sizeof(int));
    *p = 9;
    free(p); // now p is dangling