Skip to main content

IAR Embedded Workbench for RL78 5.20

LIB-putenv

In this section:
Synopsis

putenv used to set environment variable values.

Enabled by default

No

Severity/Certainty

Medium/Medium

mediummedium.png
Full description

The POSIX function putenv() is used to set environment variable values. The putenv() function does not create a copy of the string supplied to it as an argument; instead it inserts a pointer to the string into the environment array. If a pointer to a buffer of automatic storage duration is supplied as an argument to putenv(), the memory allocated for that buffer might be overwritten when the containing function returns and stack memory is recycled.

Coding standards
CERT POS34-C

Do not call putenv() with a pointer to an automatic variable as the argument

CWE 676

Use of Potentially Dangerous Function

Code examples

The following code example fails the check and will give a warning:

#include <stdlib.h>

int func(const char *var) {
  char env[1024];
  int retval = snprintf(env, sizeof(env),"TEST=%s", var);
  if (retval < 0 || (size_t)retval >= sizeof(env)) {
    /* Handle error */
  }
 
  return putenv(env);	/* BUG: automatic storage is added to the global environment */
}

The following code example passes the check and will not give a warning about this issue:

#include <stdlib.h>

int func(const char *var) {
  return setenv("TEST", var, 1);
}