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
Copy
void func1(void) {
char *temp1;
char *temp2;
temp1 = getenv("TEMP1");
printf("temp1 is %s\n", temp1);
temp2 = getenv("TEMP2");
printf("temp1 is %s\n", temp1); /* REPORT DEFECT HERE */
printf("temp2 is %s\n", temp2);
int v = strcmp(temp1, temp2); /* REPORT DEFECT HERE */
}
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
Copy
void func2(void) {
char *temp1;
char *temp2;
const char *temp = getenv("TEMP1");
temp1 = (char *)malloc(strlen(temp)+1);
printf("temp1 is %s\n", temp1);
strcpy(temp1, temp);
temp = getenv("TEMP2");
temp2 = (char *)malloc(strlen(temp)+1);
printf("temp1 is %s\n", temp1);
printf("temp2 is %s\n", temp2);
int v = strcmp(temp1, temp2);
}
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