Pages

Wednesday, January 18, 2012

"Bored Of Segmentation Fault"


Generally , the way to use "Pointers" defines , the way to tackle "Segmentation Fault".

Are you bored of segmentation fault, lets try to make it interesting. Without a fault (segmentation),we can't
learn it. :)
So,

Here is small conversation between me and my friend:


Me: (After spending almost a half day, over a silly mistake. I went to him) : Dude, I am bored of this segmentation fault ?  Help me to get rid of it.

Friend (After a cute smile) : Do you know what it is ??

Me: Yes , its a silly fault which can't be debug.

Friend: No man , You can debug it use GDB debbuger. And its just a  "attempt to access a memory that a processing unit cannot physically address".

Me(reminds me OS course): Ohoo.. Segmentation (approach to memory management and protection in the operating system). Got It. ....... But why it occurs.. even I didn't plan it to occur :)

Friend: Hmm .. Nice question .. reasons for it -
            - A buffer overflow.
            - use of unintialized pointers.
            - derefrencing Null pointers.
            - attempting a memory ehich is stranger for program.
            - exceeding the allowable stack size.

Me: Ohoo .. I think I figure out why it occurs in my code.

Here is that code(sample one):

Code #1:

                 
                     void func(string word,const int n)
                     {
                         int key[n];
                         for(int j=0;j<n*n;j++)
                         key[n]=word[j];
                     }

                     int main()
                      {
                         string word;
                         int len;
                         cin>>word;
                         len=word.length();
                         const int n=sqrt(len);
                        func(word,n);
                     }

I found segmentation fault in above code, but with small change I figure out a small lesson.

Code #2:
                    void func(string word,int n)
                     {
                         const int n = sqrt(len);
                         int key[n];
                         for(int j=0;j<n*n;j++)
                         key[n]=word[j];
                     }

Is this correct solution??-  No.
But it get you out of segmentation fault for a while.
Now question is how ??

As we use 'n' in parameter in Code #1, means it get place on stack. While in second case , on heap. 


Code # 3 (Correct solution):
               

                  void func(string word,const int n)
                     {
                         int key[n*n];
                         for(int j=0;j<n*n;j++)
                         key[n]=word[j];
                     }