IssueModification of internal buffer returned
from nonreentrant standard function occurs when the following
happens:
Nonreentrant standard functions that return a non const-qualified
pointer to an internal buffer include getenv, getlogin, crypt, setlocale, localeconv, strerror and
others.
RiskModifying 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.
FixAvoid modifying the internal buffer using the pointer returned
from the function.
Example - Modification of getenv Return Value#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 CopyOne 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);
}
}