...
Non-Compliant Code Example
In this example, the function fThe remove_spaces() function in this example accepts a pointer to a string str and a string length slen and removes the space character from the string by shifting the remaining characters towards the front of the string. The function remove_spaces() is passed a const char pointer. It then typecasts the const specification qualification away, and proceeds to modify the contents.
| Code Block |
|---|
void fremove_spaces(const char *str, intsize_t slen) { char *p = (char*)str; intsize_t i; for (i = 0; i < slen && str[i]; i++) { if (str[i] != ' ') *p++ = str[i]; } } |
...
In this compliant solution the function fremove_spaces() is passed a non-const char pointer. The calling function must ensure that the null-terminated byte string passed to the function is not const by making a copy of the string or by other means.
| Code Block |
|---|
void fremove_spaces(char *str, intsize_t slen) { char *p = str; intsize_t i; for (i = 0; i < slen && str[i]; i++) { if (str[i] != ' ') *p++ = str[i]; } } |
...
| Code Block |
|---|
int vals[] = {3, 4, 5};
memset((int *)vals, 0, sizeof(vals));
|
Otherwise, do not attempt to modify the contents of the array.
...