Bug 19975

Summary: fgets() and fread() on file without reading rights leads to SEGV
Product: Base System Reporter: chucha <chucha>
Component: miscAssignee: freebsd-bugs (Nobody) <bugs>
Status: Closed FIXED    
Severity: Affects Only Me    
Priority: Normal    
Version: Unspecified   
Hardware: Any   
OS: Any   

Description chucha 2000-07-17 08:20:01 UTC
If in program file is open, and this file does not have rights to read, fgets() and fread() will cause segmentation violation. fgets() and fread() on "failed" FILE* returned by fopen() crashes program also (use the source code below but do not 'touch test') - stupid but possible programmer's error. I don't know about read() call and others.

Fix: 

I'm not competent in fixing, but I would like to be :) Please, CC: chucha@jam.tario.ru while discussing this problem, or tell me maillist (oh, how I'm tired of all of them! ;) where this problem will be discussed. Or, if I'm really wrong and my trouble is only in my mind, let me know also... Good luck!
How-To-Repeat: 

#include <stdio.h>

extern int errno;

main() {
	FILE *file;
	char str[1024];

	file = fopen("test", "r");
//	fgets(str, sizeof(str), file);
//	fread(str, sizeof(str), 1, file);

	printf("feof(file) = %d, errno = %d, ferror(file) = %d\n",
		feof(file), errno, ferror(file));
}
Comment 1 Gregory Bond 2000-07-17 09:02:17 UTC
Read the man page for fopen().  It returns NULL if the file can't be opened.

fread() (and fgets(), and even feof() etc) can only be used on valid
filehandles.

This PR can be closed.
Comment 2 alex freebsd_committer freebsd_triage 2000-07-17 09:37:44 UTC
State Changed
From-To: open->closed

Pilot error - see audit trail: 
fopen() returns NULL if non-readable, and thus the SEGV.