CodeQL documentation

Use of dangerous function

ID: cpp/dangerous-function-overflow
Kind: problem
Security severity: 10.0
Severity: error
Precision: very-high
   - reliability
   - security
   - external/cwe/cwe-242
   - external/cwe/cwe-676
Query suites:
   - cpp-code-scanning.qls
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

This rule finds calls to the gets function, which is dangerous and should not be used. See Related rules below for rules that identify other dangerous functions.

The gets function is one of the vulnerabilities exploited by the Internet Worm of 1988, one of the first computer worms to spread through the Internet. The gets function provides no way to limit the amount of data that is read and stored, so without prior knowledge of the input it is impossible to use it safely with any size of buffer.


Replace calls to gets with fgets, specifying the maximum length to copy. This will prevent the buffer overflow.


The following example gets a string from standard input in two ways:

#define BUFFERSIZE (1024)

// BAD: using gets
void echo_bad() {
    char buffer[BUFFERSIZE];
    printf("Input was: '%s'\n", buffer);

// GOOD: using fgets
void echo_good() {
    char buffer[BUFFERSIZE];
    fgets(buffer, BUFFERSIZE, stdin);
    printf("Input was: '%s'\n", buffer);

The first version uses gets and will overflow if the input is longer than the buffer. The second version of the code uses fgets and will not overflow, because the amount of data written is limited by the length parameter.


  • Wikipedia: Morris worm.

  • E. Spafford. The Internet Worm Program: An Analysis. Purdue Technical Report CSD-TR-823, (online), 1988.

  • Common Weakness Enumeration: CWE-242.

  • Common Weakness Enumeration: CWE-676.

  • © GitHub, Inc.
  • Terms
  • Privacy