[comp.lang.c] More on that C bug...

stas@brahms.udel.edu (Stanislaus Pietrucha) (05/21/91)

/*
Well, all you doubters out there, here is the complete code.
 
It will run in a project with itself and ANSI.
 
I have cut out all the unimportant, irrelevant code and came up with this
simple version to demonstrate the bug.
 
I have fixed the things you have requested, notice the proper length field
in the fgets statement.
 
In this scenario, the code (as-is) runs.  If I try to access
p_current->last as I access all the other fields with fgets, the program
will crash (i.e. I must reboot).
 
The complete data file is attached to the end of this file.
Save it in a file and name it "stas" for simplicity.
 
Notice that none of the data file entries even approacht the bounds I've
declared in the arrays in the record structure.
 
Seperate the code from the data file and try to run it with your version
of Think C.  It will work at first, then modify it by changing the 
fgets(last,....
   to
fgets(p_current->last....
 
 
Let me know what happens!
*/
 
 
#include <stdio.h>
 
struct customer_record
	{
	struct customer_record *prev;
	struct customer_record *next;
	char number[8];
	char first[20];
	char last[24];
	char position[8];
	char team[40];
	char rookie[8];
	char sale[8];
	int quantity;
	};	
 
main()
{	
	struct customer_record *llist, *p_current;
	FILE *customer_file;
	customer_file = fopen("stas","r");	
	llist = (struct customer_record *) malloc(sizeof(struct customer_record));
	file_to_list(customer_file,llist);
	fclose(customer_file);
}
 
int file_to_list(FILE *datafile,struct customer_record *llist)
{
	struct customer_record *p_current;
	char file_header[40],last[24];
	int c = 0;
	p_current = llist; 
	p_current->prev = llist;
	fgets(file_header,40,datafile);
	printf("%s\n",file_header);
	while((c=getc(datafile)) != EOF)
	{
		ungetc(c,datafile);
		fgets(p_current->number,7,datafile);
		fgets(p_current->first,19,datafile);
		printf("this is as far as i go if the next line has fgets(p_current->last,23,datafile)\n");
		fgets(last,23,datafile);
		printf("But with fgets(last,23,datafile), I'll make it to this point!\n");
		fgets(p_current->position,7,datafile);
		fgets(p_current->team,39,datafile);
		fgets(p_current->rookie,7,datafile);
		fgets(p_current->sale,7,datafile);
		fscanf(datafile,"%d \n",&p_current->quantity);
		p_current->next = (struct customer_record *) malloc(sizeof(struct customer_record));
		p_current->next->prev = p_current;
		p_current = p_current->next;
	} 
	p_current->next = NULL;
}
 
/*Here is the data file:
1991 Customer File
1
Stas
Pietrucha
CS
Newark Devils
Y
N
5
2
Khaled
Armond
BB
Newark Devils
N
N
3
*/
 
Good luck with it
(P.S. it runs fine in either case on Unix, that's why I think it's a compiler
error with Think C.  Try it on your C compiler and tell me what happens)