title: Segmentation fault occurring in for loop (no body statements executed) C
body: <p>I am trying to write a program to convert a hexadecimal number to a decimal, and then print the decimal value. The problem I am facing is that my for loop causes a segmentation fault. </p>
  
  <pre><code>  printf("no segmentation fault so far..."); /*this printed*/
    for (i=0; (c=getchar()) != '\n'; i++) {
      printf("no segmentation fault after entering for loop"); /*this didn't print*/
  </code></pre>
  
  <p>I know this because as you can see from my code above all the code before the for loop were ran but the body wasn't executed. There could be a possibility that the for loop test case was not met and therefore it was skipped. To test for this, I put printf statements in other parts of my program as well. However, only the one above the for loop was executed. Here's my full code if it helps: </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;ctype.h&gt;
  #include &lt;math.h&gt;
  #include &lt;stdlib.h&gt;
  #define MAXLEN 100
  
  int htoi(char *s, int lim);
  void copy(char *to, char *from);
  
  int main(void) {
    char *hexArray = (char *)malloc(MAXLEN);
    htoi(hexArray, MAXLEN);
    return 0;
  }
  
  int htoi(char s[], int lim) {
    double decOutput;
    int i = 0;
    int c;
    int size = MAXLEN;
    printf("no segmentation fault so far...");
    for (i=0; (c=getchar()) != '\n'; i++) {
      printf("no segmentation fault after entering for loop");
      if (isdigit(c) || (c &gt;= 'a' &amp;&amp; c &lt;= 'f') || (c &gt;= 'A' &amp;&amp; c &lt;= 'F')) {
        if(i &gt;= size - 1) {
          size = size + MAXLEN;
          char *tmp = (char *)malloc(size);
          copy(tmp, s);
          free(s);
          s = tmp;
          printf("Buffer size increased to %d\n", size);
        }
        s[i] = c;
      }
      else {
        printf("INVALID INPUT!!! Decimal output may be inaccurate.");
      }
    }
  
    printf("exited loop");
  
    for(i = 0; s[i] != '\0'; i++) {
      printf("entered second for loop");
      if (s[i] != '0' || (s[i+1] != 'x' &amp;&amp; s[i+1] != 'X')) {
        double y = pow(16, (double)i);
        double x = s[i];
        decOutput = decOutput + pow(x, y);
      }
    }
    printf("%s", decOutput);
  
    return decOutput;
  }
  
  void copy(char *to, char *from) {
    int i = 0;
    while((to[i] = from[i]) != '\0') {
      i++;
    }
  }
  </code></pre>