What Is Dangling Pointer

A pointer pointing to a dead location than it is called dangling pointer. When ever a function returning an integer than specified return type as int. Whenever a function returning an address of integer then specified return type as int(function returns an address).

Example:



   #include<stdio.h>
               
               float *call();

               void main()

               {

                         float *ptr;

                         ptr=call();

                        clrscr();

                        printf("%d",*ptr);

               }

             float * call()

             {

                  float z=2.5;

                  ++z;

                  return &z;

             }

           


 Output: Randam value



Explanation: variable z is local variable. Its scope and lifetime are within the function call hence after returning the address of z variable z became dead and pointer is still pointing ptr is still pointing to that location.




 Solution of this problem: Make the variable z is as a static variable.

0 comments:

Post a Comment

Don't Forget to comment

About Me

My photo

HI i am mohammed  a Embedded Software Developer ,SEO specialist,Electronic engineer   Read more

ads