Showing posts with label c pointer. Show all posts
Showing posts with label c pointer. Show all posts

Thursday, January 23, 2014

Pointers: Null Pointer.

C language
C language
Hope you have read the previous post on Dangling pointer ( if not click here.). Here I am going to introduce one more pointers: Null Pointer.

Null Pointer:

The simple meaning of null pointer is, the pointer which is pointing to null value i.e we can say pointer which is pointing to nothing. Null pointer identically points to the base address of memory segment.
Examples of NULL pointer:

1. int *ptr=(char *)0;
2. float *ptr=(float *)0;
3. char *ptr=(char *)0;
4. double *ptr=(double *)0;
5. char *ptr=’\0’;
6. int *ptr=NULL;

We cannot copy any thing in the NULL pointer.

Example:

#include
 <stdio.h>
#include <string.h>
int main(){

char *ptr=NULL;
    strcpy(ptr,
"newtechshow.blogspot.com");
printf("%s",ptrr);


return 0;
}

This program will give output : null (or segment fault).

Application

  • At the end of the linked list, last node's pointer is always null. so that the linked list terminates there otherwise it goes to infinite if last pointer points to garbage values.
You can  think more applications and comment here.

Sunday, January 19, 2014

C Pointers - Dangling Pointer Problem

I found that many of under graduate students facing difficulties with pointers. In interviews generally the most of questions come from Pointers Only. Don't afraid of it . Make the basics clear by reading ANSI C or LET US C Or Try from some good video lectures. Here I am introducing some important aspects of pointers.



C pointers


Dangling Pointer Problem:

If any pointer is pointing to the memory address of a variable , but after sometime that variable is deleted from the memory. Now the pointer is still there and pointing to that particular location. Such pointer is known as dangling pointer and this problem is called dangling pointer problem.

So initially,

After the deletion of variable,
So now ptr is now become dangling pointer which is pointing to some garbage value.

Consider the following program:

#include<stdio.h>


int *foo();
void main(){

int *ptr;
ptr=foo();
printf("%d",*ptr);

}
int *foo(){

int x=25;
++x;

return &x;
}

Output of this programme:Garbage value
Here, Initially the pointer ptr is pointing the variable X of the function foo. The scope of X is only inside the function. So after returning address of X variable X became dead and pointer is still pointing ptr is still pointing to that location. 

The solution of this problem is , Make the variable X static so that it will not become dead or declare X as global variable then no such problem will arise.

You may Also like- Why C treats array parameters as pointers?