title: Memory leak in C, most likely due to realloc
body: <p>I have a program that is supposed to receive input, remember the longest string and print it out at EOF. My code works, but when run through a debugger there is a memory leak detected. I am compiling in Windows and do not have a proper debugger like Valgrind so I do not get much information about the error. The only thing I can imagine can cause this leak is the realloc() or free() function. However, I am not skilled enough in C to understand what the problem is.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;ctype.h&gt;
  #include &lt;string.h&gt;
  
  int main(void)
  {
      char *p;
      char *line;
      int sc;
      p = (char*) malloc ( sizeof(char) );
      line = (char*) malloc ( sizeof(char) );
      int count = 0;
      int max = 0;
      p[count] = 0;
      while ( ( sc = getchar()) != EOF ) {
          if ( p == NULL ) {
              p = (char*) realloc ( p, sizeof(char) );
          }
          if ( isalpha(sc) ) {
              p[count] = sc;
              count++;
              p = (char*) realloc( p, (count+1)*sizeof(char) );
              p[count] = 0;
          } else if ( sc == '\n' || sc == ' ' ) {
              if ( count &gt; max ) {
                  line = (char*) realloc( line, (count+1)*sizeof(char) );
                  strcpy( line, p );
                  max = count;
              } else if ( count == 0) {
                  printf("%d characters in longest word: %s\n", max, line);
                  free(line);
                  free(p);
                  break;
              }
              count = 0;
          }
      }
      return 0;
  }
  </code></pre>