Thursday, December 22, 2011

Pointer Types - Dangling. Wild, Bad

Discuss the following pointer types & problems regarding them

1.Dangling
2.Wild
3.Bad

Dangling Pointer:
char *someFun1()
{
char temp[ ] = “string";
return temp;
}
char *someFun2()
{
char temp[ ] = {‘s’, ‘t’,’r’,’i’,’n’,’g’};
return temp;
}
int main()
{
puts(someFun1());
puts(someFun2());
}
Output:Garbage Values
Explanation:Both   the   functions   suffer   from   the   problem   of   dangling   pointers.   In
someFun1() temp is a character array and so the space for it is allocated in heap and is
initialized with character string “string”. This is created dynamically as the function is
called, so is also deleted dynamically on exiting the function so the string data is not
available
  in  the calling  function main()   leading  to print  some garbage values.  The
function someFun2()  also suffers  from  the  same problem but   the problem can be
easily identified in this case.
BUT
char *someFun()
{
char *temp = “string constant";
return temp;
}
int main()
{
puts(someFun());
}
Output:string constant
Explanation:The program suffers no problem and gives  the output correctly because the
character  constants are stored  in code/data area and not  allocated  in stack,  so  this
doesn’t lead to dangling pointers.

Useful Links:
http://www.ccplusplus.com/2011/07/various-types-of-c-pointers.html

1 comment:

  1. Wild Pointers------------
    http://www.geeksforgeeks.org/archives/4979

    ReplyDelete