title: Got segment fault using fgets to read file
body: <p>I got segment fault when using fgets(). Does anyone have an idea where might be wrong? Thanks.
  Here is my part of code:</p>
  
  <pre><code>char buf[1024]="";
  char str[32];
  char line[32];
  
  in = fopen(argv[1], "r");
  
  while(fgets (line, sizeof(line), in) != NULL){          
          zero_pad(line, str);  // padding 0s to the line
          strcat(buf, str);
          printf("\nBuffer: %s\n", buf);
  }
  </code></pre>
  
  <p>Here is the zero_pad function：(It will simply look up the number of bits, if length of string smaller than number of bits, appending 0s at the front)</p>
  
  <pre><code>void zero_pad(char line[], char res[]){
     int num_bits, i;
     char *tmp;
     char *bin_str;
     if(line[strlen(line)-1]=='\n')  line[strlen(line)-1]='\0';
     //split by space
     tmp = strtok(line, " ");
     strcpy(bin_str, tmp);
     tmp = strtok(NULL, " ");
     num_bits = atoi(tmp);
  
     if(strlen(bin_str) &lt; num_bits) {
       char t[32]="";
       for(i=0; i&lt; (num_bits-strlen(bin_str)); i++)
            t[i] = '0';
  
       strcat(t, bin_str);
       strcpy(res, t);
     }
     else
       strcpy(res, line);   
  }
  </code></pre>
  
  <p>In GDB, I got this error message:</p>
  
  <pre><code>Program received signal SIGSEGV, Segmentation fault.
  __GI___libc_free (mem=0x7ffff7eca000) at malloc.c:2929
  2929    malloc.c: No such file or directory.
  
  (gdb) bt
  #0  __GI___libc_free (mem=0x7ffff7eca000) at malloc.c:2929
  #1  0x00007ffff7a8ff5e in _IO_free_backup_area (fp=0x603250) at genops.c:209
  #2  __GI___uflow (fp=0x603250) at genops.c:388
  #3  0x00007ffff7a83dc4 in __GI__IO_getline_info (fp=0x603250, 
      buf=0x7fffffffdf60 "1111", n=31, delim=10, extract_delim=1, eof=0x0)
      at iogetline.c:69
  #4  0x00007ffff7a82d46 in _IO_fgets (buf=0x7fffffffdf60 "1111", n=0, 
      fp=0x603250) at iofgets.c:56
  #5  0x0000000000400b8d in main ()
  </code></pre>
  
  <p>And I also tried ltrace.</p>
  
  <p>Here are the last several lines:</p>
  
  <pre><code>putchar(65, 0x7fffd69cb460, 0, 0x7fa52aa5fa50)   = 65
  printf("\nBuffer: %s\n", "0001000100010000000000001111"A
  Buffer: 0001000100010000000000001111
  ) = 38
  putchar(67, 0x7fffffda, 0x7fa52ad809e0, 37)      = 67
  fgets( &lt;no return ...&gt;
  --- SIGSEGV (Segmentation fault) ---
  +++ killed by SIGSEGV +++
  </code></pre>