CXX.STDLIB.ILLEGAL_REUSE

The CXX.STDLIB.ILLEGAL_REUSE checker reports a defect when code tries to modify a pointer returned by calling asctime(), ctime(), gmtime(), localtime(), localeconv(), getenv(), setlocale(), or strerror().

Vulnerability and risk

A second call to the above-mentioned functions may overwrite the object pointed to by the returned pointer.

Mitigation and prevention

If you want to safely reference it later, always copy and store the string into a buffer before a making a second call.

Vulnerable code example

1  void func1(void) {
2    char *temp1;
3    char *temp2;
4    temp1 = getenv("TEMP1");
5    printf("temp1 is %s\n", temp1);
6    temp2 = getenv("TEMP2");
7    printf("temp1 is %s\n", temp1);  /* REPORT DEFECT HERE */
8    printf("temp2 is %s\n", temp2);
9    int v = strcmp(temp1, temp2);    /* REPORT DEFECT HERE */
10 }

In this example, Klocwork reports a defect on lines 7 and 9 because temp1 can be overwritten as a subsequent call is made to getenv().

Fixed code example

1   void func2(void) {
2     char *temp1;
3     char *temp2;
4     const char *temp = getenv("TEMP1");
5     temp1 = (char *)malloc(strlen(temp)+1);
6     printf("temp1 is %s\n", temp1);
7     strcpy(temp1, temp);
8     temp = getenv("TEMP2");
9     temp2 = (char *)malloc(strlen(temp)+1);
10    printf("temp1 is %s\n", temp1);
11    printf("temp2 is %s\n", temp2);
12    int v = strcmp(temp1, temp2);
13  }

In the fixed example, the code copies the string temp1 that is returned by getenv() into a buffer so that the copy can be referenced later.

Related checkers

  • MISRA.STDLIB.ILLEGAL_REUSE.2012_AMD1