Main Content

Modification of internal buffer returned from non-reentrant standard function

Function attempts to modify internal buffer returned from a nonreentrant standard function

Description

This defect occurs when the following happens:

  • A nonreentrant standard function returns a pointer.

  • You attempt to write to the memory location that the pointer points to.

Nonreentrant standard functions that return a non const-qualified pointer to an internal buffer include getenv, getlogin, crypt, setlocale, localeconv, strerror and others.

Risk

Modifying the internal buffer that a nonreentrant standard function returns can cause the following issues:

  • It is possible that the modification does not succeed or alters other internal data.

    For instance, getenv returns a pointer to an environment variable value. If you modify this value, you alter the environment of the process and corrupt other internal data.

  • Even if the modification succeeds, it is possible that a subsequent call to the same standard function does not return your modified value.

    For instance, you modify the environment variable value that getenv returns. If another process, thread, or signal handler calls setenv, the modified value is overwritten. Therefore, a subsequent call to getenv does not return your modified value.

Fix

Avoid modifying the internal buffer using the pointer returned from the function.

Examples

expand all

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

void printstr(const char*);

void func() {
    char* env = getenv("LANGUAGE");
    if (env != NULL) {
        strncpy(env, "C", 1);
        printstr(env);
    }
}

In this example, the first argument of strncpy is the return value from a nonreentrant standard function getenv. The behavior can be undefined because strncpy modifies this argument.

Correction - Copy Return Value of getenv and Modify Copy

One possible solution is to copy the return value of getenv and pass the copy to the strncpy function.

#include <stdlib.h>
#include <string.h>
enum {
    SIZE20 = 20
};

void printstr(const char*);

void func() {
    char* env = getenv("LANGUAGE");
    if (env != NULL) {
        char env_cp[SIZE20];
        strncpy(env_cp, env, SIZE20);  
        strncpy(env_cp, "C", 1);        
        printstr(env_cp);
    }
}

Result Information

Group: Programming
Language: C | C++
Default: Off
Command-Line Syntax: WRITE_INTERNAL_BUFFER_RETURNED_FROM_STD_FUNC
Impact: Low

Version History

Introduced in R2015b