It is said that if a C programmer never have any problem in pointer then he is a hoax.Its confusing problematic and sometimes make ur head to go in tizzy.I will discuss here some of the not usual terms of pointers.
Dangling Pointer
Though most of us know this thing but few has a clear idea about this thing.But the most amusing thing is that we every body have used and is using this pointer unknowingly(except the most professionals one..who,I'm sure have done so previously in their life).
Dangling pointer is referred to that pointer which are pointing to a particular memory adress which has been already dereferenced already i.e., the object has been deleted without modifying the value of the pointer pointing its adress which still refers to the memory location of the dereferenced memory.
Now as the program continues it may refer that particular memory to new variables while the previous(now dangling) pointer is still referencing the memory..which might call for unpredictable behaviour.
An example of dangling pointer is when we make an array/block of memory using malloc/calloc.As soon as our function is over we call free() function to free it...but the pointer variable stays as the dangling pointer.
int main()
{
int *p;
p = (int *) malloc(sizeof(int));
/* ..... program steps .... */
free(p) ; // the pointer variable p becomes dangling
p=NULL; // the pointer variable is no longer dangling
}
Another dangling pointer example ----
int *f1(void)
{
int num = 10;
/* ...... program steps .....*/
return #
}
The above function returns the address value of the stack allocated localy declared variable num.But the stack memory is dereferenced as soon as the control shifts from the function f1 to the called function and the memory allocated for this type of variable is now dereferenced and contains garbage value.Still the value of num can be shown in the called function by accessing the returned address.Now if we call any other function say f2() and after the control comes back to the called function and we try to access the value num by its adress it will give unwanted result.This is because as soon as the second function f2() is called the variables in this function will overwrite the stack memory space which was previously taken by num variable..thus the pointer variable holding &num becomes dangling as its original pointee gets dereferenced.If we want to treat this pointer as not the dangling pointer we must declared it as static..so that the value of the variable has its scope beyond the function it is declared.
Wild pointer
Wild pointer is also another type of pointer we all use quite frequently infact every time.It is nothing but the pointer variable which has been declared but not defined.I'l give a code below to make it more simple-----
int wild(void)
{
int *p; // wild pointer
int num=1;
p=# // no more an wild pointer
}
I guess the above two is now clear to you....i'l come up with lot more
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment