C language

NULL pointer

It is the simplest pointer. The NULL pointer is a pointer which points to no where.. We can also use integer 0 in place of constant NULL.

www.exploreroots.com

Int* x=NULL;

The above statement creates a NULL pointer x.

DEREFERENCING NULL

As we know NULL pointer is actually a pointer which points to nowhere and hence we can not dereference to the NULL pointer. It is a run time ERROR to point to the NULL pointer.

Int* x=NULL;

*x=3;     DEREFERENCING NULL ERROR

After execution of statement 1, in the memory map x can be described as follow:

www.exploreroots.com

Now if we try to execute statement2, which actually is trying to assign value to the pointee of the ponter x. But as we know, the above declared pointer has no pointee, hence now we can recognize an ERROR in the above set of statements and the ERROR is called DEREFERENCING NULL

DANGLING POINTER:

The dangling pointer ERROR is an error in which we try to dereference to a memory place which has not been allocated yet.

Int* x;

*x=3;     DANGLING POINTER ERROR

After execution of statement 1, in the memory map x can be described as follow:

www.exploreroots.com

As till now we have allocated no pointee to the pointer and still we are try to dereference. As there is a random address stored in the pointer, hence if we dereference it now then we may dereference a wrong memory and hence may even corrupt some crucial application.

How ever if we only try to print the value *x then there are no chances of corrupting any application and hence it would not cause much harm but still an erroneous output. It is also called bad pointer bug.

REFERENCING DE-ALLOCATED MEMORY:

This problem occurs when the address of the local variable is returned from a function or the programmer deletes the allocated memory mistakedly.

main()

{

Int *y=abc();

*y=3;     A SERIOUS BUG (You’ll get the full explanation in the article Memory Management)

}

Int* abc()

{

Int x=7;

return (&x);

}

After the execution of statement1 in the main, the memory map is as:

www.exploreroots.com

Now we have reached the function abc (), the execution of statement1 of function abc() results into following memory map:

www.exploreroots.com

But when the function abc() returns, the address of the variable x is stored in y and INTENTION is to use x as pointee of y. But with the return of the function abc(), the stack frees the variable x. Hence memory location of x can be used somewhere else by the Operating System.

www.exploreroots.com

The non-belonging memory is the memory which doesn’t belong to the program anymore. Hence the situation now is similar to the DANGLING POINTER case. Hence the 2nd statement of main() may cause ERROR.

Note: REFER TO THE ARTICLE MEMORY MANAGEMENT FOR BETTER UNDERSTANDNG

2 Replies to “NULL pointer

  1. Pingback: skyjournals.org

Leave a Reply

Your email address will not be published. Required fields are marked *