title: Segmentation fault on fprintf when printing integer
body: <p>I keep getting a segmentation fault on the fprintf and from all my research, my sintax and initialisations are all okay. Any help will be greatly appreciated.
  NOTE: The printf("enter i") are just lines i use to check where the program fails and why.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt; 
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;math.h&gt;
  #include &lt;time.h&gt;
  #include &lt;arpa/inet.h&gt;
  #include &lt;stdbool.h&gt;
  
  void itoa(char *buf, int value);//found on stack overflow
  
  int how_many_digits(int n)
  {
  int i = 0;
  while(n &gt; 10){
      n = n / 10;
      i++;
  }
  return i + 1;   
  }
  
  int main()
  {
  srand(time(NULL));
  int server_port, main_socket, port;
  struct sockaddr_in service; 
  FILE *fileptr = NULL;
  main_socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
  service.sin_family = AF_INET;
  service.sin_addr.s_addr = inet_addr("127.0.0.1");
  do{
      printf("enter 5\n");
      port = rand() % 62974 + 1025;
      service.sin_port = htons(port);
      if(bind(main_socket, (struct sockaddr*) &amp;service, sizeof(service)) == 0) break;
      } while(1); 
  printf("enter 4\n");    
  fopen("server_port", "w");
  printf("enter 6\n");
  printf("%d\n", port);
  fprintf(fileptr,"%d", port);
  printf("enter 7\n");
  fflush(fileptr);    
  fclose(fileptr);
  printf("enter 8\n");
  listen(main_socket, 1);
  server_port = accept(main_socket, NULL, NULL);
  return 0;
  }
  </code></pre>