[comp.os.minix] Bug in ungetc.c

ceriel@cs.vu.nl (07/28/89)

There is a bug in the ungetc library routine, as demonstrated by the
following program.


#include <stdio.h>

------------8<-------------8<---------------8<------------8<------------
main()
{
	FILE *f;
	int c;

	f = fopen("/tmp/xxx", "w");
	if (f == NULL) {
		fprintf(stderr, "Could not open /tmp/xxx\n");
		exit(1);
	}
	for (c = 0; c < 10000; c++) {
		putc(c % 256, f);
	}
	fclose(f);

	f = fopen("/tmp/xxx", "r");
	if (f == NULL) {
		fprintf(stderr, "Could not re-open /tmp/xxx\n");
		exit(1);
	}
	for (c = 0; c < 10000; c++) {
		int ch, ch1;

		ch = getc(f);
		if (ch != EOF) {
			if (ungetc(ch, f) == EOF) {
				fprintf(stderr, "ungetc() failed 1, count = %d\n", c);
			}
			else {
				ch1 = getc(f);
				if (ch1 != ch) {
					fprintf(stderr, "ungetc() failed 2, count = %d\n", c);
				}
			}
		}
	}
	unlink("/tmp/xxx");
	exit(0);
}
------------8<-------------8<---------------8<------------8<------------

Below is a fix:

------------8<-------------8<---------------8<------------8<------------
*** ungetc.c.old	Mon Sep 26 13:05:25 1988
--- ungetc.c	Fri Jul 28 12:48:17 1989
***************
*** 7,13 ****
  	if ( ch < 0  || !testflag(iop,READMODE) || testflag(iop,UNBUFF) ) 
  		return( EOF );
  	
! 	if ( iop->_count >= BUFSIZ)
  		return(EOF);
  
  	if ( iop->_ptr == iop->_buf)
--- 7,13 ----
  	if ( ch < 0  || !testflag(iop,READMODE) || testflag(iop,UNBUFF) ) 
  		return( EOF );
  	
! 	if ( iop->_count > BUFSIZ)
  		return(EOF);
  
  	if ( iop->_ptr == iop->_buf)
------------8<-------------8<---------------8<------------8<------------