...
| Code Block |
|---|
|
char a[] = "string literal";
a[0] = 'S';
|
Noncompliant Code Example (POSIX)
In this noncompliant code example, a string literal is passed to the (pointer to non-const) parameter of the POSIX function mkstemp(), which then modifies the characters of the string literal:
| Code Block |
|---|
|
#include <stdlib.h>
void func(void) {
char *fname;
fname = mkstemp("/tmp/edXXXXXX");
} |
Compliant Solution (POSIX)
Instead of passing a string literal, use a named array:
| Code Block |
|---|
|
#include <stdlib.h>
void func(void) {
static char fname[] = "/tmp/edXXXXXX";
mkstemp(fname);
} |
Noncompliant Code Example (Result of strrchr())
...
| Code Block |
|---|
|
#include <stdio.h>
#include <string.h>
const char * get_dirname(const char * pathname) {
char * slash;
slash = strrchr(pathname, '/');
if (slash) {
*slash = '\0'; /* undefined behavior */
}
return pathname;
}
int main() {
puts(get_dirname(__FILE__));
return 0;
}
|
...
| Code Block |
|---|
|
#include <stdio.h>
#include <string.h>
char * get_dirname(char * pathname) {
char * slash;
slash = strrchr(pathname, '/');
if (slash) {
*slash = '\0';
}
return pathname;
}
int main() {
char pathname[] = __FILE__;
/* callingCalling get_dirname(__FILE__) may be diagnosed. */
puts(get_dirname(pathname));
return 0;
}
|
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...
...
