...
Wiki Markup |
---|
If a statement such as {{c\[0\] = 'C'}} were placed following the above declaration, the code would likely still compile cleanly, but the result of the assignment is undefined as string literals are considered constant. |
Compliant Solution
...
(immutable strings)
In this compliant solution, the characters referred to by the pointer c
are const
-qualified, meaning that any attempts to assign them to different values is an error.
Code Block | ||
---|---|---|
| ||
const char *c = "Hello"; |
Compliant Solution
...
(mutable strings)
In cases where the string is meant to be modified, use initialization instead of assignment. In this compliant solution, c
is a modifiable char
array which has been initialized using the contents of the corresponding string literal.
Code Block | ||
---|---|---|
| ||
char c[] = "Hello"; |
Wiki Markup |
---|
ThusConsequently, a statement such as {{c\[0\] = 'C'}} is valid and will dobehave whatas is expected. |
Non-Compliant Code Example 1
Although this code example is not compliant with the C99 Standard, it executes correctly if the contents of CMUfullname
are not modified
. |
Code Block | ||
---|---|---|
| ||
char *CMUfullname = "Carnegie Mellon University";
char *school;
/* Get school from user input and validate */
if (strcmp(school, "CMU")) {
school = CMUfullname;
}
|
Non-Compliant Code Example 2
Adding in the const
keyword will likely generate a compiler warning, as the assignment of CMUfullname
to school
discards the const
qualifier. Any modifications to the contents of school
after this assignment will lead to errors.
Code Block | ||
---|---|---|
| ||
const char *CMUfullname = "Carnegie Mellon University";
char *school;
/* Get school from user input and validate */
if (strcmp(school, "CMU")) {
school = CMUfullname;
}
|
Compliant Solution
The compliant solution uses the const
keyword to protect the string literal, as well as using strcpy()
to copy the value of CMUfullname
into school
, allowing future modification of school
.
...
bgColor | #ccccFF |
---|
...
Risk Assessment
Modifying string literals causes undefined behavior, resulting in abnormal program termination and denial-of-service vulnerabilities.
...