Question C fgets

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 );
}

What is the purpose of even having a variable "result" above? Nothing is being done about it. The pointer returned from fgets is stored in it, but that makes no sense.

+3
source share
3 answers

You should check this result for NULL, check the EOF condition or error, and not just ignore it. In addition, without checking the result, you make a line in the line, which may have uninitialized data, because fgets failed. Indeed, you should have after fgets:

if (!result)
{
  free(infoPtr); // To not leak the object allocated at the start
  return NULL; // Function failed
}

, fgets , , - . , , NULL. , , calloc malloc , , NULL, .

+2

, - , . NULL, , .

+2

, , . fgets result =, . , , .

0

Source: https://habr.com/ru/post/1769399/


All Articles