struct DVDInfo *ReadStruct( void ) {
struct DVDInfo *infoPtr;
int num;
char line[ kMaxLineLength ];
char *result;
infoPtr = malloc( sizeof( struct DVDInfo ) );
if ( NULL == infoPtr ) {
printf( "Out of memory!!! Goodbye!\n" );
exit( 0 );
}
printf( "Enter DVD Title: " );
result = fgets( line, kMaxLineLength, stdin );
line[ strlen( line ) - 1 ] = '\0';
infoPtr->title = MallocAndCopy( line );
printf( "Enter DVD comment: " );
result = fgets( line, kMaxLineLength, stdin );
line[ strlen( line ) - 1 ] = '\0';
infoPtr->comment = MallocAndCopy( line );
do {
printf( "Enter DVD Rating (1-10): " );
scanf( "%d", &num );
Flush();
}
while ( ( num < 1 ) || ( num > 10 ) );
infoPtr->rating = num;
printf( "\n----------\n" );
return( infoPtr );
}
为什么要在上面使用变量“result”?它并没有被使用。从fgets返回的指针被存储在其中,但它没有任何作用。
fgets
失败(注意result
从未被检查),则说line[sizeof(line)-1]=0
将会提高安全性。将其与strlen
一起使用是无意义的,不是因为fgets
总是附加一个终止零(在失败的情况下可能不会),而是因为在任何情况下,只要strlen
不会出现未定义行为,指定的字节将为零,无论fgets
是否对此有所作为。 - supercat