title: Why do I get segmentation fault in C?
body: <p><strong>Why this question is not duplicate?</strong>
  The problem can't be at <code>scanf</code>, as it is given by the hackerrank and I can't modify the code! Also, test cases are automated, given by hackerrank. We can trust them with input reading. There is some bug in my logic of finding two elements in array, couldn't find it though :|</p>
  
  <p><strong>Note:</strong> I can't modify <code>main</code> method, as mentioned earlier. Re-iterating it. Why can't I modify? It is because the method is given by the portal. I can't change it. It reads the input and calls my method through some automated scripts, I've no control over it. So, please don't tell me to modify <code>main</code> method. </p>
  
  <p>I was trying some practice problems in hackerrank in <code>C</code> language and some of the test cases started throwing <code>Segmentation fault</code> for following problem. I've tried understanding it for more than 2 hours now and couldn't think of any test case which will throw <code>segmentation fault</code>. I'm stuck :| </p>
  
  <p><strong>Problem statement:</strong></p>
  
  <blockquote>
    <p>Given an array and a number. Find if there are 2 elements in array, whose sum is equal to given number. If number are present return 1, otherwise 0.</p>
  </blockquote>
  
  <p>pretty easy, huh? I thought the same and coded it as follows,</p>
  
  <pre><code>int compFunc (const void * a, const void * b)
  {
     return ( *(int*)a - *(int*)b );
  }
  
  
  int isSumPossible(int a[], int L, int N ){
  /*L: Length of the array */
      if(a==NULL) return 0;
      if(L&lt;=1) return 0;
      int left=0, right=L-1;
  
      qsort(a,L,sizeof(int),compFunc);
  
      while(left&lt;right)
          {
          if(a[left]+a[right]==N) return 1;
          else if(a[left]+a[right]&lt;N) left++;
          else right--;    
      }
      return 0;
  }
  int main() //given by hackerrank, I can't modify main method
  {
   int N; scanf("%d", &amp;N); //fixed &amp;N - it was correctly given in code, I missed it while typing it here.
   int a[100004], i=0;
   //read input into array a, based on N
   int x;scanf("%d", &amp;x); //fixed &amp;x - it was correctly given in code, I missed it while typing it here.
   printf("%d", isSumPossible(a,N,x));
  }
  </code></pre>
  
  <p>Please assume all the header files required are included. Now, when I ran the code, most of the test cases passed and for some test cases they showed <code>Segmentation fault</code>. Unfortunately test cases aren't visible to me :|. I've gone through my code more than 10 times &amp; I don't understand in which scenario I would get <code>Segmentaion fault</code>. Can anyone help me in understand which scenario am I missing in my code and why do I see segmentation fault? </p>