...
At compile time, string literals are used to create an array of static storage duration of sufficient length to contain the character sequence and a null-termination character. It is unspecified whether these arrays are distinct. The behavior is undefined if a program attempts to modify string literals but frequently results in an access violation because string literals are typically stored in read-only memory. See also undefined behavior 33 of Annex J of the C Standard [ISO/IEC 9899:2011].
The returned value of the library functions strpbrk(), strchr(), strrchr(), wcspbrk(), wcschr(), and wcsrchr() and pointer to (or array of) const characters shall be treated as a string literal.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h>
#include <string.h>
const char *get_dirname(const char *pathname) {
char *slash;
slash = strrchr(pathname, '/');
if (slash) {
*slash = '\0'; /* undefinedUndefined 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__;
/* Calling get_dirname(__FILE__) may be diagnosed. */
puts(get_dirname(pathname));
return 0;
}
|
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
Can detect simple violations of this rule | |||||||||
| 157 S | Partially implemented | |||||||
| PRQA QA-C |
| 0556 | Partially implemented | ||||||
|
|
...
Bibliography
| [ISO/IEC 9899:2011] | Annex J, subclause J.2, "Undefined Behavior" | ||
| [Plum 1991] | Topic 1.26, "Strings—String Literals" | ||
| [Summit 1995] | comp.lang.c FAQ list, Question 1.32 | [ISO/IEC 9899:2011] | Annex J, J2, "Undefined behavior"
...