Thursday, February 23, 2012

Journey of a pointer from NULL to FREE

Why C ???

In this dynamic IT world new languages come every day and get obsolete, so there must be     something in  C which has remained there for 4 decades and more and even today there   is hardly any language which can match its strength.Though C is simple it is one of the most powerful languages ever created. Wiki puts it this way:
 C is the most commonly used programming language for writing operating systems. Unix was the first operating system written in C. Later Microsoft Windows, Mac OS X, and GNU/Linux were all written in C. Not only is C the language of operating systems, it is the precursor and inspiration for almost all of the most popular high-level languages available today. In fact, Perl, PHP, and Python are all written in C .

There must be a reason. Indeed there is !!!  C is the most elegant one. Not only that,Once you learn C, making the jump to Java or C# (and others too) is fairly easy, because a lot of the syntax is common.

But then , why POINTERS in C ???

Acoording to Yashwant kanetkar  :
A C programmer without knowledge of pointers is like a fish which doesn't know how to swim. He needs command over pointers to be able to exploit the immense potential of C. Pointers are all about power and punch. But then its not easy being comfortable with the usage of pointers. No matter how much time you have spent with it, you will always find some application of it that would leave you guessing !!!

 No Pointers => No data structures .You need to have a fair bit of command on pointers to get along with the implementation of linked lists and trees . So pointers are immensely important and to be called a good C programmer one needs to master them. At least to get through the recruiting process of good technical firms (for software developers) one needs the knowledge of pointers.  There is a dark side to it as well , pointers are  error prone. So  be very sure you need it when you actually want to use it in an application .

A piece of Advice:

Understanding pointers in C is not a skill, it's an aptitude. So be sure you try to understand them , not learn them. There is no end to the questions that can be framed on pointers, there is no end to the situations you will get trapped into when you try debugging some of your codes that involve pointers. Trust me these are very tricky. Dont try to remember that so and so happens in xyz situation and those kind of stuff. Some common situations you land yourself into while you battle with the pointers  in C  are :



Last but certainly not the least, try compiling the codes you come across in your own compiler or for this matter you may also find ideone useful, I certainly do :) Play with them, Try debugging them . This is the best way to learn!!!

The biggest Quesstion - How  ???

If you are  decent with the understanding of C and struggling with pointers , this blog is specially designed for you. There is a huge volume of material available on internet, then why this one ? The problem is- most of them are simply BADLY EXPLAINED ONES !!! . I am by no means  the best person to explain the nuts and bolts of pointers , but I  have a read a lot of them and therefore I can point you to some of the best ones available .  Before you attack pointers if you want to brush up  C quickly, you may  love to go through this. But then it is not mandatory to do that. Here is a list of things you would like to own if you have made up your mind to master pointers today:

  1. Pointers and memory  by Nick Parlante (from stanford): This document explains how pointers and memory work and how to use them—from the basic concepts through all the major programming techniques. For each topic there is a combination of discussion, sample C code, and drawings. Go through it word-by-word. Get into the habit of drawing memory diagrams as explained here. I bet it will help you a lot.

  2. The C Programing Language by Brain W Kernighan and Dennis M Ritchie (K & R). It is undoubtedly the best text available on C and one of the thinnest too :D .Grab a copy of it from  amazon.com or may be flipkart (preferable if you stay in India). If you dont want to buy a book , go through the reviews . Whether you buy it or not, you will be impressed for sure. And try doing the exercises as well.

  3. K & R is not for  beginners . So , if you are one , you may also go through  Understanding Pointers in C  by Yashwant Kanetkar. This book covers everything that has anything to do with pointers in a simple to understand way. The topics covered include: 

    • Pointers and Arrays

    • Pointers and Structures

    • Pointers and Dynamic Memory Allocation

    • Pointers to Functions

    • Pointers and Variable Argument Lists

    • Practical use of Pointers

    • Pointers and Doubly linked Lists

    • Pointers and Circular Lists

    • Pointers and Binary Trees

    • Pointers and Threaded Binary Trees



  4. Once you are done with these , you will really feel comfortable implementing your data structures viz.. linked list or binary trees etc.


In reference to the point no (4) above , You may first like to go through these :


All three references above are from Nick Parlante himself and once you are done with "Pointers and Memory" (numbered (1) above) , these are excellent materials for practice .

Some Good Habits :

  1. Initialize pointers when declared.Never leave pointer variables uninitialized - things wouldn't be too bad if uninitialized pointers always contained random values - the vast majority of random values are illegal pointer values and will cause the program to crash as soon as they are used. The problem is that uninitialized variables tend to take on the value of other, previously used pointer variables. These problems are very difficult to debug.If you don't know what else to initialize a pointer to, initialize it to zero. Zero is guaranteed to be an illegal address.

  2. Zero pointers out after you use them.Similarly, always zero a pointer variable once the pointer is no longer valid. This is particularly the case when you return a block of memory to the heap using delete; always zero the pointer after returning heap memory.

  3. Allocate memory from the heap and return it to the heap at the same "level" to avoid memory leaks.Always try to return a memory block to the heap at the same level of abstraction as you allocated it. This generally means trying to delete the memory at the same level of function calls.

  4. Catch an exception to delete memory when necessary.Don't forget that an exception can occur at almost any time. If you intend to catch the exception and continue operating (as opposed to letting the program crash), make sure that you catch the exception and return any memory blocks to the heap before the pointers that point to them go out of scope and the memory is lost.

  5. Make sure that the types match exactly.Always make sure that the types of pointers match the required type. Don't recast a pointer without some specific reason. Consider the following:
    void fn(int* p);
    void myFunc()
    {
    char c = 'a';
    char* pC = &c;
    fn((int*)pC);
    }

    The above function compiles without complaint since the character pointer pC has been recast to an int* to match the declaration of fn(int*); however, this program will almost surely not work. The function fn() is expecting a pointer to a full 32-bit integer and not some rinky-dink 8 bit char. These types of problems are very difficult to sort out.


Congratulations !!! You are now set to conquer the world :D

Comments/Suggestion, if any : Please feel free to offer any general comments/suggestions/advice you may have about material or articles here. Llinks to websites that you feel would be a good reference for others to visit would really help .  ******************************************************************************************************************************************************************************************

3 comments: