...
In C, function arguments are passed by value rather than by reference. While a function may change the values passed in, these changed values are discarded once the function returns. For this reason, many programmers assume a function will not change its arguments, and declaring the function's parameters as const
is unnecessary.
Code Block |
---|
void foo(int x) {
x = 3; /* persists only until the function exits */
/* ... */
}
|
Pointers behave in a similar fashion. A function may change a pointer to reference a different object, or NULL, yet that change is discarded once the function exits. Consequently, declaring a pointer as const
is unnecessary.
Code Block |
---|
void foo(int *x) {
x = NULL; /* persists only until the function exits */
/* ... */
}
|
...
Code Block |
---|
|
void foo(int *x) {
if (x != NULL) {
*x = 3; /* visible outside function */
}
/* ... */
}
|
...
Code Block |
---|
|
void foo(const int *x) {
if (x != NULL) {
*x = 3; /* generates compiler error */
}
/* ... */
}
|
...
Code Block |
---|
|
void foo(const int * x) {
if (x != NULL) {
printf("Value is %d\n", *x);
}
/* ... */
}
|
...
Code Block |
---|
|
char *strcat_nc(char *s1, char *s2);
char *str1 = "str1";
const char *str2 = "str2";
char str3[9] = "str3";
const char str4[9] = "str4";
strcat_nc(str3, str2); /* Compiler warns that str2 is const */
strcat_nc(str1, str3); /* Attempts to overwrite string literal! */
strcat_nc(str4, str3); /* Compiler warns that str4 is const */
|
...
Code Block |
---|
|
char *strcat(char *s1, const char *s2);
char *str1 = "str1";
const char *str2 = "str2";
char str3[9] = "str3";
const char str4[9] = "str4";
strcat(str3, str2);
/* Args reversed to prevent overwriting string literal */
strcat(str3, str1);
strcat(str4, str3); /* Compiler warns that str4 is const */
|
...
Tool | Version | Checker | Description |
---|
| | | |
| | | |
| | | |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...