Main Content

Use of indeterminate string

Use of unvalidated buffer from fgets-family function

Description

This defect occurs when you do not check if a write operation using an fgets-family function such as:

char * fgets(char* buf, int n, FILE *stream)
succeeded and the buffer written has valid content, or you do not reset the buffer on failure. You then perform an operation that assumes a buffer with valid content. For instance, if the buffer with possibly indeterminate content is buf (as shown above), the checker raises a defect if:

  • You pass buf as argument to standard functions that print or manipulate strings or wide strings.

  • You return buf from a function.

  • You pass buf as argument to external functions with parameter type const char * or const wchar_t *.

  • You read buf as buf[index] or *(buf + offset), where index or offset is a numerical value representing the distance from the beginning of the buffer.

Risk

If an fgets-family function fails, the content of its output buffer is indeterminate. Use of such a buffer has undefined behavior and can result in a program that stops working or other security vulnerabilities.

Fix

Reset the output buffer of an fgets-family function to a known string value when the function fails.

Examples

expand all

#include <stdio.h>
#include <wchar.h>
#include <string.h>
#include <stdlib.h>

#define SIZE20 20

extern void display_text(const char *txt);

void func(void) {
    char buf[SIZE20];
	
	/* Check fgets() error */
    if (fgets (buf, sizeof (buf), stdin) == NULL)
    {
        /* 'buf' may contain an indeterminate string.  */
        ;
    }
	/* 'buf passed to external function */
    display_text(buf); 
}
        
      

In this example, the output buf is passed to the external function display_text(), but its value is not reset if fgets() fails.

Correction — Reset fgets() Output on Failure

If fgets() fails, reset buf to a known value before you pass it to an external function.

#include <stdio.h>
#include <wchar.h>
#include <string.h>
#include <stdlib.h>

#define SIZE20 20

extern void display_text(const char *txt);

void func1(void) {
    char buf[SIZE20];
	/* Check fgets() error */
    if (fgets (buf, sizeof (buf), stdin) == NULL)
    {
		/* value of 'buf' reset after fgets() failure. */
        buf[0] = '\0';
    }
	/* 'buf' passed to external function */
    display_text(buf); 
} 

Result Information

Group: Programming
Language: C | C++
Default: Off
Command-Line Syntax: INDETERMINATE_STRING
Impact: Medium

Version History

Introduced in R2017b