...
Code Block | ||||
---|---|---|---|---|
| ||||
void f() { char *path = NULL; /* Avoid assuming $PATH is defined or has limited length */ const char *temp = getenv("PATH"); if (temp != NULL) { path = (char*) malloc(strlen(temp) + 1); if (path == NULL) { /* Handle error condition */ } else { strcpy(path, temp); } /* Use path */ free(path); } } |
Compliant Solution (POSIX or C2x)
In this compliant solution, the strdup()
function is used to dynamically allocate a duplicate of the string:
Code Block | ||||
---|---|---|---|---|
| ||||
void f() { char *path = NULL; /* Avoid assuming $PATH is defined or has limited length */ const char *temp = getenv("PATH"); if (temp != NULL) { path = strdup(temp); if (path == NULL) { /* Handle error condition */ } /* Use path */ free(path); } } |
Risk Assessment
Making assumptions about the size of an environmental variable can result in a buffer overflow.
...