The headers buffer contains also potentially binary data the CGI program is sending, and it needs to be sent out later. Use add_data() to cache data so the cgi output does not get corrupted on first zero byte. add_data() still always terminates the buffer with zero, so strstr() can used safely. diff -ru mini_httpd-1.25.orig/mini_httpd.c mini_httpd-1.25/mini_httpd.c --- mini_httpd-1.25.orig/mini_httpd.c 2016-07-07 06:02:52.000000000 +0300 +++ mini_httpd-1.25/mini_httpd.c 2016-11-09 12:01:19.025607907 +0200 @@ -1998,7 +1998,7 @@ add_str( &headers, &headers_size, &headers_len, (char*) 0 ); for (;;) { - r = read( rfd, buf, sizeof(buf) - 1 ); + r = read( rfd, buf, sizeof(buf) ); if ( r < 0 && ( errno == EINTR || errno == EAGAIN ) ) { sleep( 1 ); @@ -2009,8 +2009,7 @@ br = &(headers[headers_len]); break; } - buf[r] = '\0'; - add_str( &headers, &headers_size, &headers_len, buf ); + add_data( &headers, &headers_size, &headers_len, buf, r ); if ( ( br = strstr( headers, "\015\012\015\012" ) ) != (char*) 0 || ( br = strstr( headers, "\012\012" ) ) != (char*) 0 ) break;